Flatten - Combining Arrays with forEach()
var data = [[1,2,3], [4,5,6], [7,8,9]];
function arrayAdd(aOfAs) {
var acc = [];
aOfAs.forEach(function(a) {
a.forEach(function(el) {
acc.push(el);
;})
;});
return acc;
}
arrayAdd(data);
> [1,2,3,4,5,6,7,8,9]
Same Thing - Flatten with reduce()
var data = [[1,2,3],[4,5,6],[7,8,9]];
var flattenedData = data.reduce(function(acc, value) {
return acc.concat(value);
}, []);
console.log(flattenedData);
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
Processing every element of an array with reduce()
var data = [1,2,3,4,5];
var doubled = data.reduce(function(acc, value) {
acc.push(value * 2);
return acc;
}, []);
console.log(doubled);
> [2, 4, 6, 8, 10]
Selecting some elements of an array with reduce()
var data = [1,2,3,4,5];
var evens = data.reduce(function(acc, value) {
if (value % 2 === 0) {
acc.push(value);
}
return acc;
}, []);
console.log(evens);
> [2, 4]
Same Thing Using filter()
var evenFiltered = data.filter(function(item) {
return item % 2 === 0;
});
console.log(evenFiltered);
[2, 4]
Filtered and Mapped
var filteredAndMapped = data.filter(function(value) {
return value % 2 == 0;
}).map(function(value) {
return value * 2;
});
console.log(filteredAndMapped);
> [4, 8]