Reducing Values by Reduce Method
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
Flatten Array of Objects
The example below shows how to flatten an array of objects into a single object.
1let array=[{
2 key:'Moiz',
3 value:1
4},
5{
6 key:"Hello",
7 value:2
8},
9{
10 key:"Hassan",
11 value:9
12},
13]
14let result=array.reduce((obj,present)=>({...obj,[present.key]:
15 present.value}),{})
16console.log("result",result)
17
Map Using Reduce
As another example of using the initial value parameter, consider the task of calling a function on an array of items, returning the results in a new array. Since arrays are ordinary values and list concatenation is an ordinary function, we can use reduce to accumulate a list, as the following example demonstrates:
1let array=[{
2 key:'Moiz',
3 value:1
4},
5{
6 key:"Hello",
7 value:2
8},
9{
10 key:"Hassan",
11 value:9
12},
13]
14function map(array, fn) {
15 return array.reduce(function(newList, item) {
16 return newList.concat(fn(item));
17 }, []);
18}
19let a=map(array,function(n){return n.value * n.value})
20console.log(a)
21
Finding Unique Values
Here is an example that uses reduce to return the unique numbers to an array. An empty array is passed as the second argument and is referenced by prev
1var arr = [1, 2, 1, 5, 9, 5];
2let arrSort=arr.reduce((prev, number) => {
3 if(prev.indexOf(number) === -1) {
4 prev.push(number);
5 }
6 return prev;
7}, []);
8console.log("arrSort",arrSort)
9
Array Sum
This method can be used to condense all values of an array into a single value:
1
2 var arr = [1, 2, 1, 5, 9, 5];
3let sumArray=arr.reduce(function(a,b){
4 return a+b
5})
6console.log("sumAraay",sumArray)
7let sumArry=[10].reduce(function(a,b){
8 return a+b
9},1)
10console.log("sumArray2",sumArry)
11
About
Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.
Follow him on TwitterHassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.
Follow him on TwitterTags
Click to see all tutorials tagged with: