How do I check if an array contains only unique values in JavaScript?
Benjamin C
benjamin c profile pic

To check if an array contains only unique values in JavaScript, you can use various approaches. Here are a few methods: 1. Using a Set:

1
2
3
4
5
6
7
8
9

   function hasUniqueValues(arr) {
     const uniqueSet = new Set(arr);
     return uniqueSet.size === arr.length;
   }

   const array = [1, 2, 3, 4, 5];
   console.log(hasUniqueValues(array));  // Output: true
   

TheSet data structure allows storing unique values. By creating aSet from the array and comparing its size with the length of the array, we can determine if all values are unique. 2. Using a for loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

   function hasUniqueValues(arr) {
     for (let i = 0; i < arr.length; i++) {
       for (let j = i + 1; j < arr.length; j++) {
         if (arr[i] === arr[j]) {
           return false;
         }
       }
     }
     return true;
   }

   const array = [1, 2, 3, 4, 4, 5];
   console.log(hasUniqueValues(array));  // Output: false
   

This method uses nested loops to compare each element with the rest of the array. If a duplicate element is found, the function returnsfalse. Otherwise, if no duplicates are found, it returnstrue. 3. Using theevery() method withindexOf():

1
2
3
4
5
6
7
8

   function hasUniqueValues(arr) {
     return arr.every((value, index, array) => array.indexOf(value) === index);
   }

   const array = [1, 2, 3, 4, 4, 5];
   console.log(hasUniqueValues(array));  // Output: false
   

Theevery() method checks if every element in the array satisfies a given condition. In this case, we check if the index of the current element is equal to the first index of that element in the array. If the condition holds true for all elements, the function returnstrue. These methods provide different ways to check if an array contains only unique values in JavaScript. Choose the one that suits your preference and requirements.