Check array only contains unique value javascript
You can check if an array contains only unique values in JavaScript by using a Set, which inherently only allows unique values.
Here’s how:
function isUnique(arr) {
return new Set(arr).size === arr.length;
}
- This function takes an array (arr) as an argument.
- It creates a new Set from the array, which will only contain unique values.
- It checks if the size of the Set is equal to the length of the original array.
- If these values are equal, it means that all values in the array were unique, so the function returns true.
- If they are not equal, it means that some values in the array were not unique, so the function returns false.
For example, calling isUnique([1, 2, 3, 4, 5])
will return true
,
but calling isUnique([1, 2, 3, 3, 5])
will return false
.