Checking for uniqueness in an array in JavaScript


We are required to write a JavaScript function that takes in an array of numbers as the first and the only argument. The function should return true if all the numbers in the array appear only once (i.e., all the numbers are unique), and false otherwise.

For example −

If the input array is −

const arr = [12, 45, 6, 34, 12, 57, 79, 4];

Then the output should be −

const output = false;

because the number 12 appears twice in the array.

Example

The code for this will be −

 Live Demo

const arr = [12, 45, 6, 34, 12, 57, 79, 4];
const containsAllUnique = (arr = []) => {
   const { length: l } = arr;
   for(let i = 0; i < l; i++){
      const el = arr[i];
      const firstIndex = arr.indexOf(el);
      const lastIndex = arr.lastIndexOf(el);
      if(firstIndex !== lastIndex){
         return false;
      };
   };
   return true;
};
console.log(containsAllUnique(arr));

Output

And the output in the console will be −

false

Updated on: 26-Feb-2021

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements