Last active
February 21, 2025 08:41
-
-
Save trantronghien/1525bd94f686a3daf385e0d43fb1d896 to your computer and use it in GitHub Desktop.
reduce function
This file contains hidden or 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
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