I need to write a function in JavaScript which would return a boolean after checking if all values of a given array are unique. Examples
[1,2,3,4] true
[1,2,1,4] false, since the array has value '1' twice
I need to write a function in JavaScript which would return a boolean after checking if all values of a given array are unique. Examples
[1,2,3,4] true
[1,2,1,4] false, since the array has value '1' twice
You compare length of your array and size of the Set which always contains uniq entries.
const isUnique = (arrToTest) =>
arrToTest.length === new Set(arrToTest).size
console.log(isUnique([1,1,2,3]));
console.log(isUnique([1,2,3]));
You can sort
and check for each sibling.
var array1 = [1,2,3,4];
var array2 = [1,2,1,4];
function decorate(array) {
array.uniques = function() {
this.sort();
for (var i = 0; i < this.length; i++) {
if (this[i + 1] === this.length) return true;
if (this[i] === this[i + 1]) return false;
}
}
}
decorate(array1);
decorate(array2);
console.log(array1.uniques());
console.log(array2.uniques());
You can use a custom object
function checkUnique(array)
{ var i,obj={};
for(i=0;i<array.length;i++)
{ if(obj[array[i]])
return false;
obj[array[i]]=true;
}
return true;
}
console.log(checkUnique([1,2,3,4]));
console.log(checkUnique([1,2,1,4]));