Why doesn't this return true?

Comparing a given array to the same array sorted in ascending order.

Should return true but instead returns false

EDIT:
I ran join('')to each array and it fixed the problem.
I also tried [1] == [1] and that returned false.

Can some explain why this happens?

// arr = [1, 2, 3, 4]

function inAscOrder(arr) {
  let asc = [...arr].sort((a, b) => {
    return a - b;
  });

  return arr == asc; //should return true
}

console.log(inAscOrder([1, 2, 3, 4])); // returns false

You can’t compare arrays with comparison operators like above.

The best way is to loop through both arrays and compare each value.

Loop feels excessive.

I’ve always done it this way:

JSON.stringify(a) == JSON.stringify(b)

Edit

I just read the SO question properly.

I can see why you’d need to loop if you had very complicated arrays, possible containing objects or deep nesting.

However, in such a case I would probably have to carefully examine whether comparing two such arrays was actually the best solution to whatever problem I was actually trying to solve. I suspect there are very few occasions upon which such a comparison is necessary, but maybe I’m just not sufficiently imaginative to think of them :slight_smile:

1 Like

Remember that with non-primitive data types, that variable doesn’t compare the data itself but the address of the memory where the data is stored. When you compare the variables you are asking if they point to the same memory. In this case it is two different memory locations (that contain the same data) so the addresses are different.

Either of the two solutions offered will work. I don’t know know if one is better than the other - we’d have to test them.