Checking for uniqueness in an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

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
raja
Published on 26-Feb-2021 08:33:11
Advertisements