Given two arrays: actual and expected; is there a more efficient way to write the is equal check?

actual.reduce((total, element)=> {
        if (element !== expected[actual.indexOf(element)]) {
            return total = false;
        } else return total;
  • 7
    \$\begingroup\$ Can you add a bit more detail and possibly a working example? Are you checking if all items in one array are present in another? Are duplicate values allowed? Are any of the arrays sorted? \$\endgroup\$ – Slai Nov 12 '17 at 21:57
  • \$\begingroup\$ you can also do it like JSON.stringify(actual.sort()) === JSON.stringify(expected.sort()) \$\endgroup\$ – Goldy Jan 25 '19 at 8:29

A couple of things about your implementation:

  1. indexOf will return the index of the first matching element. If there are duplicate elements it will fail- for example, the. comparison of 1,2,1,4 and 1,2,3,4.
  2. Most (if not all) JavaScript array methods pass the current index to the callback function, so you could write your code as:

    actual.reduce((total, element, index)=> {
  3. Ideally, you want to stop when you have found a pair that doesn't match.

However I would do this using the every method:

let equal = actual.length == expected.length 
         && actual.every((element, index)=> element === expected[index] );

(Or possibly with a plain old for loop)


Not the answer you're looking for? Browse other questions tagged or ask your own question.