array.reduce EXAMPLES Flashcards
const numbers = [1,2,3];
ADD NUMBERS with REDUCE
console.log(x);// 6
numbers.reduce((accumulator, currentValue)=> accumulator + currentValue);
const numbers = [ {x:1}, {x:2}, {x:3} ];
ADD NUMBERS with REDUCE var sum = [{x: 1}, {x: 2}, {x: 3}].reduce
console.log(x);// 6
var initialValue = 0;
((accumulator, currentValue)
=> accumulator + currentValue.x;
,initialValue);
console.log(sum) // logs 6
const numbers = [[1,2],[3,4]];
Flatten array
console.log(x);// [1, 2, 3, 4];
numbers.reduce((a, b) a.concat(b));
const numbers = [[1],[3,4]];
let x = numbers.reduce((accumulator, currentValue)=> accumulator + currentValue);
console.log(x);// returns
13, 4
var names = [‘Alice’, ‘Bob’, ‘Tiff’, ‘Bruce’, ‘Alice’];
var countedNames = //Counting instances of values in an object
// countedNames is: // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
names.reduce(function (allNames, name) { if (name in allNames) { allNames[name]++; } else { allNames[name] = 1; } return allNames; }, {});
var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']; var myOrderedArray = //Remove duplicate items in array
console.log(myOrderedArray);
myArray.reduce(function (accumulator, currentValue) {
if (accumulator.indexOf(currentValue) === -1) {
accumulator.push(currentValue);
}
return accumulator
}, [])
const numbers = [1,2,3]; numbers.reduce((accumulator, currentValue)=> accumulator + currentValue);
//WRITE OUT OLD WAY
let sum =
let sum = 0;
for (let n of numbers)
sum+= n;
WHY DOES THIS RETURN AN ARRAY
const numbers = [1, 2, 3];
function sum(...arg){ console.log(arg); return arg.reduce((a, cv) => a + cv); };
console.log(sum([1,2,3]));
…arg turns an array into an array.
const numbers = [1, 2, 3];
function sum(...arg){ // Write the If statement to check to see if arg is an array and set it to a array
return arg.reduce((a, cv) => a + cv);
};
console.log(sum([1]));
if (Array.isArray(arg[0]))
arg = […arg[0]];