If we have an array, and we want to find the item(s) that appears once in the array.
const arr = [1,1,2,2,4,5,4]
The single item in the array above is 5, how can we solve this using JavaScript? We can use a hashmap aka Hash table, we need to convert the array to an object with the item as the key and their number of occurrence as the value.
const hashMap = {};
for (i of arr) {
if (hashMap[i]) {
hashMap[i]++;
} else {
hashMap[i] = 1;
}
}
console.log(hashMap)
//
We declared an empty object, and loop through the array, our array item is passed in as the key, and we check to see if this item appears in the array more than once, if it does, we increment the value, if it appears once we set the value to 1.
We get the result below
{ '1': 2, '2': 2, '4': 2, '5': 1 }
As we can see 5 is the only number that appears once in the array, with a value of 1.
We need to loop through the object and get the keys with the value of 1, then push it into an array.
const single = []
for (i in hashMap) {
if (hashMap[i] === 1) {
single.push(Number(i));
}
}
console.log(single)
The single item in the array is a string, it is converted to a number as we push it into the array.
We get the value below.
[ 5 ]
Thank you for reading.
Top comments (5)
Great example of using a hash table to tally and track data.
If you're interested, you could also use the Array sort() and filter() methods to quickly extract unique elements.
use the sort method to place all identical elements in adjacent indexes of a new array.
Use filter to generate another array which only includes elements which are different to the elements immediately before and after them in the sorted array (and are therefore unique).
Postscript
Removing duplicate items from your array
EG convert [1,2,2,1,4,8,8,9] to [1,2,4,8,9]
Create a new set from your original array and then spread the set into a new array.
Nice post! The great benefit to using a
HashMap
in this way is that the entire operation takesO(n)
time, whereas sorting would usually take something likeO(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:Thanks for sharing!
I am usually not a fan of ugly one liners, but if you want it concise:
const arr = [1,1,2,2,4,5,4];
let singles=[];
arr.forEach((el,index,array)=>{
let single=array.filter(element => element === el);
if(single.length === 1){
singles.push(single[0])
}
});