Skip to content

Instantly share code, notes, and snippets.

@arturparkhisenko
Last active October 21, 2016 21:18
Show Gist options
  • Save arturparkhisenko/f29a408fa8de141f7e13ef72673d9313 to your computer and use it in GitHub Desktop.
Save arturparkhisenko/f29a408fa8de141f7e13ef72673d9313 to your computer and use it in GitHub Desktop.
js-search-and-reduce
// 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