Skip to content

Instantly share code, notes, and snippets.

@bouwe77

bouwe77/reducers.js Secret

Created Mar 25, 2021
Embed
What would you like to do?
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