-2

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
Sergey Pleshakov
  • 7,964
  • 2
  • 17
  • 40
  • Additionally `myArray.some((x, i, l) => l.indexOf(x) !== i)` is true iff `myArray` contains a duplicate. – CRice Feb 20 '18 at 23:03
  • Similar to https://stackoverflow.com/questions/7376598/in-javascript-how-do-i-check-if-an-array-has-duplicate-values – A J Feb 20 '18 at 23:11

3 Answers3

2

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]));
Karen Grigoryan
  • 5,234
  • 2
  • 21
  • 35
  • Of course, this won't work in all browsers (points dagger at internet exploder < 11) – Jaromanda X Feb 20 '18 at 23:49
  • @JaromandaX Of course if you check it in ie6 it also won't work, of course if you don't use babel or other transpilers and polyfills in your build chain in your day to day flow when using es6+, you are still likely to have problems with various old browser versions. This goes without saying, and half of the answers on stackoverflow that include es6+ answers imply that. – Karen Grigoryan Feb 21 '18 at 07:16
  • 2
    I know, I just like to remind people that internet exploder must die – Jaromanda X Feb 21 '18 at 10:51
0

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());
Ele
  • 33,468
  • 7
  • 37
  • 75
0

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]));
guigoz
  • 674
  • 4
  • 21