Skip to content

Instantly share code, notes, and snippets.

@trantronghien
Last active November 20, 2022 07:53
Show Gist options
  • Save trantronghien/1525bd94f686a3daf385e0d43fb1d896 to your computer and use it in GitHub Desktop.
Save trantronghien/1525bd94f686a3daf385e0d43fb1d896 to your computer and use it in GitHub Desktop.
reduce function
let array = [4, 5, 6]
let initialValue = 1 // giá trị bắt đầu
let rs = array.reduce((previousValue, item, index, arrayReduce) => {
// console.log(item); // giá trị của item tại index, item = array[index]
// console.log(previousValue); // đầu tiên previousValue = initialValue, previousValue = return callbackReduce()
// console.log(index); // index của array
// console.log(arrayReduce); // arrayReduce == array
let result = previousValue + item
return result
}, initialValue)
console.log(rs); // rs = initialValue + array[0]+ array[1] + array[2] = 16
// ví dụ xử lý với object
const playerProfile = [
{ name: "Ronaldo", team: "Juventus " },
{ name: "Messi", team: "Barcelona" },
{ name: "Mane", team: "Liverpool" }
];
const getMapFromArray = data => {
return data.reduce((obj, item) => {
obj[item.name] = { team: item.team };
return obj
}, {})
}
const playerProfileModified = getMapFromArray(playerProfile)
console.log(playerProfileModified)
Result:
{
Ronaldo: { team: 'Juventus ' },
Messi: { team: 'Barcelona' },
Mane: { team: 'Liverpool' }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment