Javascript – Check if all values of array are equal

javascriptjquery

I need to find arrays where all values are equal. What's the fastest way to do this? Should I loop through it and just compare values?

['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false

Best Answer

const allEqual = arr => arr.every( v => v === arr[0] )
allEqual( [1,1,1,1] )  // true

Or one-liner:

[1,1,1,1].every( (val, i, arr) => val === arr[0] )   // true

Array.prototype.every (from MDN) : The every() method tests whether all elements in the array pass the test implemented by the provided function.