DEV Community

Discussion on: Finding a single item in an array

Collapse
 
shaileshcodes profile image
Shailesh Vasandani

Nice post! The great benefit to using a HashMap in this way is that the entire operation takes O(n) time, whereas sorting would usually take something like O(n log n) time.

You could probably also condense it to a one-liner (or maybe two-liner) and keep the O(n) property by doing something like this:

const arr = [1,1,2,2,4,5,4];
const singles = [];
const map = {};

arr.forEach(el => map[el] ? map[el]++ : map[el] = 1);
Object.keys(map).forEach((k) => map[k] == 1 ? singles.push(k) : null);
Enter fullscreen mode Exit fullscreen mode

Thanks for sharing!