So basically why this post will be useful to you? Before you deep dive into the blog blink your eye here for a second!
let me answer, Suppose you have your array, something looks like this: #1
const array = [
{ name: "ram", properties: "4gb" },
{ name: "size", properties: "2xl" },
{ name: "color", properties: "red" },
{ name: "size", properties: "3xl" },
{ name: "size", properties: "3xl" },
{ name: "ram", properties: "4gb" },
{ name: "size", properties: "2xl" },
{ name: "color", properties: "red" },
{ name: "color", properties: "blue" },
{ name: "color", properties: "black" },
{ name: "size", properties: "3xl" },
];
and you want your array seems something like this :
[
{ name: "ram", properties: [ "4gb", "3gb" ]},
{ name: "size", properties: [ "2xl", "3xl" ]},
{ name: "color", properties: [ "red", "blue", "black" ]},
]
Can you think about a second and build your own logic without help from any resources ? explore : scroll !
aww 😢 returned scroll ;
Let's have another practical use case of Reduce : #2
const peoples = [
{ name: "Nischal", heightInFeet: 5.8, age: 16 },
{ name: "Sudip", heightInFeet: 5.7, age: 16 },
{ name: "Nuri", heightInFeet: 6.1, age: 20 },
{ name: "Ankita", heightInFeet: 4.6, age: 19 },
];
and you want to create a new array where users are stored in the index of age :
console.log(filteredDeoples)Here you will see 16, 19, and 21 as the key of the object which has a value of an array of users, so how can you fulfill this via reduce ?
Lastly!
Bonus for you! forEach ~ first array data
const count = {};
array.forEach(function (i) {
if (!count[i.name]) {
count[i.name] = 0;
}
count[i.name]++;
});
console.log(count);
Output :
Lets' use another case for reduce and I promise this is the last one 😢😆
3
const users = [
{ name: "Nischal", heightInFeet: "5.8", age: 16 },
{ name: "Sudip", heightInFeet: "5.4", age: 21 },
{ name: "Nuri", heightInFeet: "6.1", age: 19 },
{ name: "Ankita", heightInFeet: "4.4", age: 19 },
];
Here above we have an array of users and each has the value of name, heightInFeet which represent their height in feet lastly we have the age of each user stored in the array,
and Here we faced, that we need to filter the users via the height, ok confusing? if then I will elaborate I want the object of height like 5, 6, and so on which should contain the users who have the height in that range so without looking at my code you can try to decode using simple code, firstly you can definitely try without using reduce array function and after that, you can use the reduce function of the array to do the job!
Here I have the code of the section top users array,
const res = users.reduce((usersHeight, curr) => {
const { heightInFeet } = curr;
const height = Math.floor(heightInFeet).toString() + "ft";
if (usersHeight[height] == null) usersHeight[height] = [];
usersHeight[height].push(curr);
return usersHeight;
}, {});
The Output of the above console.log(res) is :
ok, let's DECODE how this reduce function works after a lot of examples and code we have practiced and tried now, pretend you completely know about the reduce function in javascript I will try to explain using the diagram.
Reduce itself the name says it is reducing the array according to your needs, at simple it just mean that reduces the array, into the smaller and needed one !
What MDN docs says?
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
Simplify reduce
reduce method takes two different parameters, first one is the function here in the case we have arrow function and second parameter is going to be your starting value!
accumulator : It accumulates and reduce the return value !
currentValue : It is the each individual item we are looping through.
currentIndex : It is the third last parameter of the index inside the array
array : It is the last parameter of the method and accepts array
reduce((accumulator, currentValue, currentIndex, array) =>
{ /* … */ }, initialValue)
but that one is harder let's understand it from the basics,
here is the code of the first example ~ #1
const array = [
{ name: "ram", properties: "4gb" },
{ name: "size", properties: "2xl" },
{ name: "color", properties: "red" },
{ name: "size", properties: "3xl" },
{ name: "size", properties: "3xl" },
{ name: "ram", properties: "4gb" },
{ name: "size", properties: "2xl" },
{ name: "color", properties: "red" },
{ name: "color", properties: "blue" },
{ name: "color", properties: "black" },
{ name: "size", properties: "3xl" },
];
const result = array.reduce((acc, curr) => {
const { name, properties } = curr;
if (!acc.some((item) => item.name === name)) {
acc.push({ name, properties: [properties] });
} else {
const index = acc.findIndex((item) => item.name === name);
if (!acc[index].properties.includes(properties)) {
acc[index].properties.push(properties);
}
}
return acc;
}, []);
here is how you can accomplish it without using reduce array method,
const temp = [];
const filteredValues = [];
array.forEach((val) => {
// -1 represents not match found, it checks true if not the match found
if (temp.indexOf(val.name) === -1) {
temp.push(val.name);
filteredValues.push({ name: val.name, properties: [] });
}
});
array.forEach((v) => {
filteredValues.forEach((item) => {
if (v.name === item.name) {
if (item.properties.indexOf(v.properties) === -1) {
item.properties.push(v.properties);
temp.push(item.name);
}
}
});
});
console.log(filteredValues);
here is the code for the second example ~ #2
let result = users.reduce((groupedPeoplesViaAge, person) => {
const { age } = person;
if (groupedPeoplesViaAge[age] == null) groupedPeoplesViaAge[age] = [];
groupedPeoplesViaAge[age].push(person);
return groupedPeoplesViaAge;
}, {});
Practice more and learn more! Explore, learn, Earn 🚀
Bonus use case and understanding of reduce in Javascript !
const arr1 = [
{ name: 'Nischal Dahal', goals: 0, assists: 0, points: 0 },
{ name: 'Sudip Mahato', goals: 2, assists: 1, points: 3 },
{ name: 'Ankita ', goals: 1, assists: 1, points: 2 },
{ name: 'Santosh Dahal', goals: 5, assists: 7, points: 12 },
{ name: 'neeswebservices', goals: 5, assists: 7, points: 12 },
{ name: 'Cat', bones: 100000, goals: 5, assists: 7, points: 12 },
];
const arr2 = [
{ name: 'Noob player', goals: 3, assists: 3, points: 6, ppg: 0, ppa: 0, pims: 0, },
{ name: 'Achuta Ghimire', goals: 1, assists: 4, points: 5, ppg: 0, ppa: 1, pims: 0 },
{ name: 'Bidhan Acharya', goals: 0, assists: 0, points: 0, ppg: 0, ppa: 0, pims: 0, },
{ name: 'Pandey Sudip', goals: 0, assists: 0, points: 0, ppg: 0, ppa: 0, pims: 0, },
];
function addItUp(...arraysOfData) {
const data = arraysOfData.flat();
const tally = data.reduce(function(tallyArray, item) {
// first check if this person is new
const { name, ...points } = item;
console.log(`Working on ${name}`);
console.log(points);
tallyArray[name] = tallyArray[name] || {};
// Loop over each of their properties and add them up
Object.entries(points).forEach(([key, val]) => {
if(tallyArray[name][key]) {
// Already exists, so we increment the value by the next line
tallyArray[name][key] = tallyArray[name][key] + val;
} else {
// brand new, set it to that value!
tallyArray[name][key] = val;
}
})
return tallyArray;
}, {});
return tally;
}
const result = addItUp(arr1, arr2);
console.table(result);
Output:
If you didn't understand please let me know via connect .
Thank you for scrolling till here 🤣 ! do check my Github and Mail for contact!
1, #2, and #3 mean the connection you can search and go to a particular section!
Give a follow, 👏 if the content helped you!
connect : info@nischal-dahal.com.np
Instagram: https://instagram.com/neeswebservices
Github: https://github.com/neeswebservices
facebook: https://facebook.com/102.nees.418
This is my first blog, feedback is accepted if you have one💗.
Top comments (0)