Picking out uniques from an array in JavaScript



Suppose we have an array that contains duplicate elements like this βˆ’

const arr = [1,1,2,2,3,4,4,5];

We are required to write a JavaScript function that takes in one such array and returns a new array. The array should only contain the elements that only appear once in the original array.

Therefore, let’s write the code for this function βˆ’

Example

The code for this will be βˆ’

const arr = [1,1,2,2,3,4,4,5];
const extractUnique = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      if(arr.lastIndexOf(arr[i]) !== arr.indexOf(arr[i])){
         continue;
      };
      res.push(arr[i]);
   };
   return res;
};
console.log(extractUnique(arr));

Output

The output in the console will be βˆ’

[ 3, 5 ]
Updated on: 2020-10-21T12:37:34+05:30

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements