Skip to content

Instantly share code, notes, and snippets.

@TravelingMan
Last active January 11, 2016 20:01
Show Gist options
  • Save TravelingMan/777afa9ffaaa87dd9fd1 to your computer and use it in GitHub Desktop.
Save TravelingMan/777afa9ffaaa87dd9fd1 to your computer and use it in GitHub Desktop.
JS - Condense arrays with reduce, concatenate arrays
var oldArray = [1,2,3];
var newArray = [];
var concatMe = [4,5,6];
newArray = oldArray.concat(concatMe);
var array = [4,5,6,7,8];
var singleVal = 0;
/* Call reduce with a callback that includes an accumulator (previousVal in this case) and the current value (currentVal)
Note that reduce() has an optional second argument to set the initial value of the accumulator. If left out, the
initial value will be the 1st array element, and currentVal will begin with the 2nd array element.
*/
singleVal = array.reduce(function(previousVal, currentVal) {
return previousVal + currentVal;
}, 0);
// Another example with all four arguments (previousValue, currentValue, currentIndex, array):
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {
return previousValue + currentValue;
});
@TravelingMan
Copy link
Author

To flatten an array, you can use reduce as follows:

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
  return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]

Also, you can use an arrow function to get a one-liner for a simple evaluation:

[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment