DEV Community

Discussion on: Finding a single item in an array

Collapse
 
gilfewster profile image
Gil Fewster

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
Collapse
 
gilfewster profile image
Gil Fewster

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