-
-
Save lucianobarauna/537b459cfe91a3e2fe104cbcc2c79340 to your computer and use it in GitHub Desktop.
Artigos | Array.reduce - O canivete suíço da programação funcional | Array multidimensional
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 users = [ | |
{ | |
name: 'User #1', | |
bookmarks: [ | |
{ title: 'Movie #1', id: 1 }, | |
{ title: 'Movie #6', id: 6 }, | |
{ title: 'Movie #3', id: 3 }, | |
] | |
}, | |
{ | |
name: 'User #2', | |
bookmarks: [ | |
{ title: 'Movie #1', id: 1 }, | |
{ title: 'Movie #4', id: 4 }, | |
{ title: 'Movie #6', id: 6 }, | |
{ title: 'Movie #2', id: 2 }, | |
] | |
} | |
]; | |
const bookmarks = users | |
.map(user => user.bookmarks) /* from: [ { #: [{...}] }, { #: [{...}] } ] */ | |
.reduce((bookmarks, movies) => { /* to: [ [{...}], [{...}] ] */ | |
return bookmarks | |
.concat(movies.filter((movie) => { | |
return bookmarks | |
.map(movie => movie.id) | |
.indexOf(movie.id) === -1; | |
})); | |
}, []); /* from: [ [{...}], [{...}] ] */ | |
/* to: [ {...}, {...} ] */ | |
/* | |
#bookmarks | |
[ | |
{ title: 'Movie #1', id: 1 }, | |
{ title: 'Movie #6', id: 6 }, | |
{ title: 'Movie #3', id: 3 }, | |
{ title: 'Movie #4', id: 4 }, | |
{ title: 'Movie #2', id: 2 }, | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment