-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdeepclone.html
More file actions
85 lines (67 loc) · 2.19 KB
/
deepclone.html
File metadata and controls
85 lines (67 loc) · 2.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja" dir="ltr" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Deep Clone</title>
</head>
<body>
<!-- Slideshow container -->
<div>
Deep Clone
</div>
<script>
const todos = [
{ id: 1, title: 'learn javascript', price: 200},
{ id: 2, title: 'learn angular', price: 500},
{ id: 3, title: 'learn vue', price: 100},
{ id: 4, title: 'learn abc', price: 100},
] // a => b, c, d // global scope
// const clonedTodos = [...todos]; // shallow clone
const clonedTodos = [...todos]; // deep clone
const idBE = 2;
const todoIndex = clonedTodos.findIndex(todo => todo.id === idBE)
clonedTodos[todoIndex].title = 'node js'
console.log('res: ', { todos, clonedTodos })
// using by reduce to total -> 800
const totalPrice = todos.reduce((accumulator, todo) => {
return accumulator + todo.price;
}, 0);
// grouping object by a property
const people = [
{ name: "Alice", age: 21 },
{ name: "Max", age: 20 },
{ name: "Jane", age: 20 },
];
function grouping(data, property) {
return data.reduce((acc, currItem) => {
const key = currItem[property]; // currItem['age'] = 21
const currGroup = acc[key] ?? [];
return {
...acc,
[key]: currGroup.concat(currItem)
};
}, {})
}
const resGrouping = grouping(people, 'age')
console.log('resGrouping: ', resGrouping)
/*
case1: people, 'age'
{
21: [ ... ],
20: [ ... ],
}
*/
// counting values of object
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
const nameCounting = names.reduce((accumulator, name) => {
if (accumulator[name]) {
accumulator[name] += 1;
} else {
accumulator[name] = 1;
}
return accumulator;
}, {});
console.log(nameCounting);
</script>
</body>
</html>