Skip to content

Instantly share code, notes, and snippets.

@darrennolan
Created July 4, 2016 23:31
Show Gist options
  • Save darrennolan/ceffed8873a5cd93daa1bf946fa97901 to your computer and use it in GitHub Desktop.
Save darrennolan/ceffed8873a5cd93daa1bf946fa97901 to your computer and use it in GitHub Desktop.
let myArray = ['Pizza', 'Apple', 'Banana'];
let combinedString = myArray.reduce((combinedString, item, index) => {
if (index != 0) {
return `${combinedString} and ${item}`;
} else {
return item;
}
}, '');
console.log(combinedString); // Pizza and Apple and Banana
let myArray = [{id: 4457, name: 'Pizza'}, {id: 5678, name: 'Apple'}, {id: 2234, name: 'Banana'}];
let objectByName = myArray.reduce((objectByName, item) => {
objectByName[item.name] = item.id;
return objectByName;
}, {});
console.log(objectByName); // Object {Pizza: 4457, Apple: 5678, Banana: 2234}
let myArray = [1, 3, 5, 10];
let arrayFilled = myArray.reduce((collector, number) => {
return collector.concat(number, 0);
}, []);
console.log(arrayFilled); // [1, 0, 3, 0, 5, 0, 10, 0]
@darrennolan
Copy link
Author

darrennolan commented Jul 4, 2016

map gives 1 to 1 return of something in place of what the array item's value is.

filter will remove items not fulfilling a requirement.

reduce kind of sort of provides both these things - and can return whatever format you want.
Just keep in mind, you always start with your 'current value'. That current value, in the examples above start as '', {} and [] respectively. You could even start with a pre-filled array. .reduce(funcToDoStuff, initialValue).

On each iteration, you must return your same/new/modified object (in the last example I called it a collector). If you don't return anything, on the next iteration, the collector var would have been undefined.

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