728x90
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
// Create keyed object from array | |
// importance: 4 | |
// Let’s say we received an array of users in the form {id:..., name:..., age:... }. | |
// Create a function groupById(arr) that creates an object from it, with id as the key, and array items as values. | |
// function groupById(users) { | |
// return users.reduce((obj, user) => { | |
// obj[user.id] = user; | |
// return obj; | |
// }, {}); | |
// } | |
let users = [ | |
{id: 'john', name: "John Smith", age: 20}, | |
{id: 'ann', name: "Ann Smith", age: 24}, | |
{id: 'pete', name: "Pete Peterson", age: 31}, | |
]; | |
let usersById = groupById(users); | |
console.log(usersById); | |
/* | |
// after the call we should have: | |
usersById = { | |
john: {id: 'john', name: "John Smith", age: 20}, | |
ann: {id: 'ann', name: "Ann Smith", age: 24}, | |
pete: {id: 'pete', name: "Pete Peterson", age: 31}, | |
} | |
*/ |
'Algorithm > JavaScript(Node.js)' 카테고리의 다른 글
The Modern JS Tutorial: Map and Set: filter anagrams (0) | 2021.10.06 |
---|---|
The Modern JS Tutorial: Map and Set: filter unique array members (0) | 2021.10.06 |
The Modern JS Tutorial: array-methods: filter unique array members (0) | 2021.09.22 |
The Modern JS Tutorial: array-methods: Get average age (0) | 2021.09.22 |
The Modern JS Tutorial: array-methods: shuffle an array (0) | 2021.09.21 |