Last active
January 11, 2016 20:01
-
-
Save TravelingMan/777afa9ffaaa87dd9fd1 to your computer and use it in GitHub Desktop.
JS - Condense arrays with reduce, concatenate arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var oldArray = [1,2,3]; | |
var newArray = []; | |
var concatMe = [4,5,6]; | |
newArray = oldArray.concat(concatMe); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To flatten an array, you can use reduce as follows:
Also, you can use an arrow function to get a one-liner for a simple evaluation: