-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6.Reduce.js
More file actions
59 lines (53 loc) · 1.29 KB
/
6.Reduce.js
File metadata and controls
59 lines (53 loc) · 1.29 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
/*
* Author: Marc Ciruelos Santos
* Date: 21-02-2024
* Description: Array reduce() => Examples using the reduce() function with an objects array.
*/
const books = [
{
id: 1,
title: "Thinking, fast and slow",
author: "Daniel Kahneman",
price: 12.5,
format: "paperback",
genres: ["Education", "Psychology"],
pages: 731,
},
{
id: 2,
title: "Deep work. Rules for focused success in a distracted world",
author: "Cal Newport",
price: 25.69,
format: "hardcover",
genres: ["Education", "Business"],
},
{
id: 3,
title: "Rules for life: An antidote to chaos",
author: "Jordan B. Peterson",
price: 12.86,
format: "paperback",
genres: ["Business", "Study Skills"],
},
];
// Reduce() --> Creates a new array with a criterion
// Create a new array with the books genres
console.log(
books.reduce((allGenres, book) => {
return [...allGenres, ...book.genres];
}, [])
);
// Remove repeated genres
console.log(
books.reduce((allGenres, book) => {
return Array.from(new Set([...allGenres, ...book.genres]));
}, [])
);
// Alternative: filter
console
.log(
books.reduce((allGenres, book) => {
return [...allGenres, ...book.genres];
}, [])
)
.filter((book, index, self) => index === self.indexOf(book));