Last active
December 3, 2019 15:34
-
-
Save akari0624/2b86f5b4410b7658ebd52f573fef0fdd to your computer and use it in GitHub Desktop.
array.prototype.flatMap Set good usage scenario example
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
<!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> |
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
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