-
-
Save bouwe77/587a0fd9211a2310ca087abb92031e2a to your computer and use it in GitHub Desktop.
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
const pets = [ | |
{ name: 'Doug', kind: 'dog', photo: '🐶' }, | |
{ name: 'Katy', kind: 'cat', photo: '🐱' }, | |
{ name: 'Carl', kind: 'cat', photo: '🐈' }, | |
{ name: 'Patti', kind: 'parrot', photo: '🦜' }, | |
]; | |
// Mapping: | |
const photos = []; | |
for (pet of pets) { | |
photos.push(pet.photo); | |
} | |
console.log(photos); | |
const photos2 = pets.map((pet) => pet.photo); | |
console.log(photos2); | |
// Filtering: | |
const cats = []; | |
for (pet of pets) { | |
if (pet.kind === 'cat') cats.push(pet); | |
} | |
console.log(cats); | |
const cats2 = pets.filter((pet) => pet.kind === 'cat'); | |
console.log(cats2); | |
// Combining (chaining) array.filter and array.map: | |
const catPhotos = pets | |
.filter((pet) => pet.kind === 'cat') | |
.map((cat) => cat.photo); | |
console.log(catPhotos); | |
// Reducing: | |
let countCats = 0; | |
for (pet of pets) { | |
if (pet.kind === 'cat') countCats++; | |
} | |
console.log(countCats); | |
const reducer = function (total, pet) { | |
if (pet.kind === 'cat') return total + 1; | |
return total; | |
}; | |
const initialValue = 0; | |
let countCats2 = pets.reduce(reducer, initialValue); | |
console.log(countCats2); // 2 | |
let countCats3 = pets.reduce( | |
(total, pet) => (pet.kind === 'cat' ? total + 1 : total), | |
0 | |
); | |
console.log(countCats3); | |
const petsObjectExample = { | |
dogs: [{ name: 'Doug', photo: '🐶' }], | |
cats: [ | |
{ name: 'Katy', photo: '🐱' }, | |
{ name: 'Carl', photo: '🐈' }, | |
], | |
parrots: [{ name: 'Patti', photo: '🦜' }], | |
}; | |
console.log(petsObjectExample); | |
const petsObject2 = pets.reduce((obj, pet) => { | |
const key = pet.kind + 's'; | |
obj[key] = obj[key] || []; | |
obj[key].push({ name: pet.name, photo: pet.photo }); | |
return obj; | |
}, {}); | |
console.log(petsObject2); | |
// useReducer | |
function countReducer(state, action) { | |
switch (action.type) { | |
case 'increment': | |
return { ...state, count: state.count + 1 }; | |
case 'decrement': | |
return { ...state, count: state.count - 1 }; | |
default: | |
return state; | |
} | |
} | |
const state = [ | |
{ type: 'increment' }, | |
{ type: 'increment' }, | |
{ type: 'decrement' }, | |
{ type: 'increment' }, | |
].reduce(countReducer, { count: 0 }); | |
console.log(state); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment