Forum Discussion

npise's avatar
npise
New Contributor II
5 years ago
Solved

Check if all values of array are equal

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
  • 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)

2 Replies

  • 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)