-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeyed-object-array.js
More file actions
45 lines (33 loc) · 1.19 KB
/
keyed-object-array.js
File metadata and controls
45 lines (33 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 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.
// For example:
// 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);
// /*
// // 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},
// }
// */
// Such function is really handy when working with server data.
// In this task we assume that id is unique. There may be no two array items with the same id.
// Please use array .reduce method in the solution.
let users = [
{id: 'john', name: "John Smith", age: 20},
{id: 'ann', name: "Ann Smith", age: 24},
{id: 'pete', name: "Pete Peterson", age: 31},
];
function groupById(array) {
return array.reduce((obj, value) => {
obj[value.id] = value;
return obj;
}, {})
}
let usersById = groupById(users);
console.log(usersById);