Skip to content

Instantly share code, notes, and snippets.

@coelhucas
Last active October 16, 2021 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coelhucas/6ff345747cd2e42fb4a5d386093dea1d to your computer and use it in GitHub Desktop.
Save coelhucas/6ff345747cd2e42fb4a5d386093dea1d to your computer and use it in GitHub Desktop.
javascript reduce
const components = [
{
name: 'Button',
styles: {
color: 'white',
backgroundColor: 'black',
borderRadius: '20px'
}
},
{
name: 'TextInput',
styles: {
color: 'black',
border: '2px solid'
}
},
{
name: 'Checkbox',
styles: {
color: 'deeppink'
}
}
];
const getComponentsMetadata = () => (
components.reduce((acc, current) => ({
...acc,
[current.name]: {
...current.styles
}
}), {})
);
{
Button: {
color: "white",
borderRadius: "20px",
backgroundColor: "black"
},
TextInput: { … },
CheckBox: { … }
}
const arr = [1, 2, 3, 4, 5, 6];
const sum = arr.reduce((acc, current) => acc + current, 10);
console.log(sum); // 31
const reducer = (accumulator, current, currentIndex, array) => {
const prefix = currentIndex === array.length - 1 ? 'e ' : ', ';
return `${accumulator}${prefix}${current}`;
}
function getJoinedNames(names) {
return names.reduce(reducer);
}
console.log(getJoinedNames(['zezinho', 'luizinho', 'iguinho')]); // 'zezinho, luizinho e iguinho'
const arr = [1];
cont result = arr.reduce((acc, current) => 2 * (acc + current));
// 1 (valor inicial), 2 (valor atual) -> 1 + 2
// 3 (valor anterior), 3 (valor atual) -> 3 + 3
// 6 (valor anterior), 4 (valor atual) -> 6 + 4
// 10 (valor anterior), 5 (valor atual) -> 10 + 5
// 15 (valor anterior), 6 (valor atual) -> 15 + 6
console.log(sum); // 21
const arr = [1, 2, 3, 4, 5, 6];
const sum = arr.reduce((acc, current) => acc + current);
const arr = [1, 2, 3, 4, 5, 6];
let sum = 10;
arr.forEach(value => {
sum += value;
})
console.log(sum); // -> 31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment