Skip to content

Instantly share code, notes, and snippets.

@akari0624
Last active December 3, 2019 15:34
Show Gist options
  • Save akari0624/2b86f5b4410b7658ebd52f573fef0fdd to your computer and use it in GitHub Desktop.
Save akari0624/2b86f5b4410b7658ebd52f573fef0fdd to your computer and use it in GitHub Desktop.
array.prototype.flatMap Set good usage scenario example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
const friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'Bible'],
age: 18
}];
var allBooks1 = friends.reduce((prev, curr) => [...prev, ...curr.books], []).reduce((init, current) => {
if (init.indexOf(current) < 0) {
init.push(current);
}
return init;
}, []);
const allBooks2 = [...new Set(friends.flatMap(friend => friend.books))]
console.log(allBooks1);
console.log(allBooks2);
</script>
<script id="jsbin-source-javascript" type="text/javascript">
const friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'Bible'],
age: 18
}];
var allBooks1 = friends.reduce((prev, curr) => [...prev, ...curr.books], []).reduce((init, current) => {
if (init.indexOf(current) < 0) {
init.push(current);
}
return init;
}, []);
const allBooks2 = [...new Set(friends.flatMap(friend => friend.books))]
console.log(allBooks1);
console.log(allBooks2);</script></body>
</html>
const friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'Bible'],
age: 18
}];
var allBooks1 = friends.reduce((prev, curr) => [...prev, ...curr.books], []).reduce((init, current) => {
if (init.indexOf(current) < 0) {
init.push(current);
}
return init;
}, []);
const allBooks2 = [...new Set(friends.flatMap(friend => friend.books))]
console.log(allBooks1);
console.log(allBooks2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment