Last active
October 21, 2016 21:18
-
-
Save arturparkhisenko/f29a408fa8de141f7e13ef72673d9313 to your computer and use it in GitHub Desktop.
js-search-and-reduce
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
// https://twitter.com/forwebdev/status/789538916898660352 | |
const userIds = [1, 5, 1, 2, 9, 9, 6, 4, 3, 5]; | |
console.log(userIds.slice().sort(); | |
// -> [1, 1, 2, 3, 4, 5, 5, 6, 9, 9] | |
function getUniqueItems(array) { | |
const = uniqueItemsHash = array.reduce((acc, item) => { | |
acc[item] = item; | |
return acc; | |
}, {}); | |
return Object.keys(uniqueItemsHash).map(key => uniqueItemsHash[key]); | |
} | |
const uniqueUsersIds = getUniqueItems(userIds); | |
console.log(uniqueUsersIds.slice().sort()); | |
// -> [1, 2, 3, 4, 5, 6, 9] | |
// https://twitter.com/forwebdev/status/789477769247854592 | |
// for primitives | |
const userIds = [1, 5, 1, 2, 9, 9, 6, 4, 3, 5]; | |
const uniqueUsersIds = userIds.filter((id, index, array) => array.indexOf(id) === index); | |
console.log(uniqueUsersIds.slice().sort()); | |
// -> [1, 2, 3, 4, 5, 6, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment