cancel
Showing results for 
Search instead for 
Did you mean: 

Check if all values of array are equal

npise
New Contributor II

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
1 ACCEPTED SOLUTION

del
Contributor III

The Array.reduce function appears to be effective for this:

shortened syntax:

$myArray.reduce((av,cv,ci,ar) => (av && (ar[0] == cv)), true)

or verbose syntax:

$myArray.reduce((accumulatedValue,currentValue,currentIndex,originalArray) => (accumulatedValue && (originalArray[0] == currentValue)), true)

View solution in original post

2 REPLIES 2

del
Contributor III

The Array.reduce function appears to be effective for this:

shortened syntax:

$myArray.reduce((av,cv,ci,ar) => (av && (ar[0] == cv)), true)

or verbose syntax:

$myArray.reduce((accumulatedValue,currentValue,currentIndex,originalArray) => (accumulatedValue && (originalArray[0] == currentValue)), true)

npise
New Contributor II

Thank you. this worked!!