MOCKSTACKS
EN
Questions And Answers

More Tutorials









Javascript Reducing values

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.


Array Sum

This method can be used to condense all values of an array into a single value:

[1, 2, 3, 4].reduce(function(a, b) {
 return a + b;
});

Output

"10"

Optional second parameter can be passed to reduce(). Its value will be used as the first argument (specified as a) for the first call to the callback (specified as function(a, b)).

[2].reduce(function(a, b) {
 console.log(a, b); // prints: 1 2
 return a + b;
}, 1);

Output

"3"

Flatten Array of Objects

The example below shows how to flatten an array of objects into a single object

var array = [{
 key: 'one',
 value: 1
}, {
 key: 'two',
 value: 2
}, {
 key: 'three',
 value: 3
}];

array.reduce(function(obj, current) {
 obj[current.key] = current.value;
 return obj;
}, {});

Output

{
one: 1,
two: 2,
three: 3
}

array.reduce((obj, current) => Object.assign(obj, {
 [current.key]: current.value
}), {});

Output

{
one: 1,
two: 2,
three: 3
}

array.reduce((obj, current) => ({...obj, [current.key]: current.value}), {});

Output

{
one: 1,
two: 2,
three: 3
}

Find Min or Max Value

We can use the accumulator to keep track of an array element as well. Here is an example leveraging this to find the min value:


var arr = [4, 2, 1, -10, 9]
arr.reduce(function(a, b) {
 return a < b ? a : b
}, Infinity);

Output

-10

Find 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.


var arr = [1, 2, 1, 5, 9, 5];
arr.reduce((prev, number) => {
 if(prev.indexOf(number) === -1) {
 prev.push(number);
 }
 return prev;
}, []);

Output

[1, 2, 5, 9]


Conclusion

In this page (written and validated by ) you learned about Javascript Reducing values . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Sorting Arrays.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.