Skip to content

Instantly share code, notes, and snippets.

@jordyvandomselaar
Created July 19, 2021 08:35
Show Gist options
  • Save jordyvandomselaar/22992d1c6ac65cd2b5361a219d8a3b10 to your computer and use it in GitHub Desktop.
Save jordyvandomselaar/22992d1c6ac65cd2b5361a219d8a3b10 to your computer and use it in GitHub Desktop.
// Reduce loops through an array, giving you access to each item. It'll also give access to the current "result".
// You can specify an initial value which reduce will use to initialize the "result" variable.
const myArray = [
1,
2,
3
];
const initialValue = [];
const myNewValue = myArray.reduce((result, currentArrayItem) => {
// For the first iteration, result is "initialValue". So result is an empty array. currentArrayItem is "1" because
// that's the first item in myArray.
// Whatever you return here, is the "result" variable for the next iteration. You could return "1" and then for the
// next iteration, "result" would be "1". In this case, we want to return our current result but also add something
// to it.
//
// We push a new entry into our result array with value currentArrayItem + 2. For our first iteration that would be
// 1 + 2 = 3. Result is now an array with one item with value 3.
//
// The next iteration now has the "result" variable which is an array with one entry with value "3" and "currentArrayItem"
// is now "2".
//
// This goes on for every item in "myArray".
result.push(currentArrayItem + 2);
return result;
}, initialValue);
console.log(myNewValue); // [ 3, 4, 5 ]
// Of course, initialValue can be anything. You could make it an object and then build it from an array like so:
const myArray = [
{
id: 1,
name: "Jordy"
},
{
id: 2,
name: "Mandy"
}
];
// Now let's turn that array into an object that is keyed by the id and has values containing our names.
// {1: "Jordy", 2: "Mandy"}
const initialValue = {}; // We start with an empty object
const myNewObject = myArray.reduce((result, currentArrayItem) => {
// Assign the current array item's name to the key in our new object:
result[currentArrayItem.id] = currentArrayItem.name;
// Make sure to return the object so we can use it in the next iteration.
return result;
}, initialValue);
console.log(myNewObject); // { '1': 'Jordy', '2': 'Mandy' }
// You could also use a regular 'ole for loop to achieve the same thing (but with different scoping)
const myArray = [
{
id: 1,
name: "Jordy"
},
{
id: 2,
name: "Mandy"
}
];
const myNewObject = {}; // This is also our initial value now.
for(const arrayItem of myArray) {
myNewObject[arrayItem.id] = arrayItem.name;
}
console.log(myNewObject); // { '1': 'Jordy', '2': 'Mandy' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment