Finding a single item in an array
/[Abejide Femi Jr]\s/

/[Abejide Femi Jr]\s/ @bjhaid_93

About: passionate javascript dev

Location:
lagos
Joined:
May 8, 2018

Finding a single item in an array

Publish Date: Jan 1 '21
22 5

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]
Enter fullscreen mode Exit fullscreen mode

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)
// 
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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 ]
Enter fullscreen mode Exit fullscreen mode

Thank you for reading.

Comments 5 total

  • Gil Fewster
    Gil FewsterJan 1, 2021

    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.

    1. use the sort method to place all identical elements in adjacent indexes of a new array.

    2. 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).

    const animals = ["panther","cat","dog","monkey","cat"]
    const nums = [1,2,3,4,1,1,2,6,7,2,4,5,9];
    
    const getUniqueElements = (arr) => {
      const sorted = arr.sort();
      return sorted.filter((item, index) => {
        return (item != sorted[index-1]) && (item != sorted[index+1])
      });
    }
    
    
    console.log(getUniqueElements(animals)); // ['dog' ,'monkey', 'panther']
    console.log(getUniqueElements(nums)); // [3, 5, 6, 7, 9]
    
    Enter fullscreen mode Exit fullscreen mode
    • Gil Fewster
      Gil FewsterJan 2, 2021

      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.

      const animals = ["cat","dog","monkey","cat"]
      const nums = [1,7,2,4,1,1,2,7,2,4];
      
      const uniqueAnimals = [...new Set(animals)]; // ["cat","dog","monkey"]
      const uniqueNums = [...new Set(nums)]; // [1,7,2,4]
      
      
      Enter fullscreen mode Exit fullscreen mode
  • neoan
    neoanJan 1, 2021

    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]
    const singles = [];
    arr.forEach(el => arr.filter(el2 => el == el2).length == 1) ? singles.push(el) : null)
    
    
    Enter fullscreen mode Exit fullscreen mode
  • Shailesh Vasandani
    Shailesh VasandaniJan 1, 2021

    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!

  • farhajhussain44
    farhajhussain44Jan 1, 2021

    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])
    }
    });

Add comment