1

const arr = [{name:'Suzanne'},{name:'Jim'},{name:'Trevor'},{name:'Amanda'}];

arr.sort((a,b)=>a.name > b.name);

I want to sort elements(objects) in the array name-alphabetically(A->Z). When I use the code in node(v8.4.0) and safari development tool(console), it works well.

But it doesn't work in chrome development tool-console(v70.0.3538.110). There is a result of code in chrome console.

enter image description here

In my opinion, the code is not wrong. I don't know why the code doesn't work well.

2
  • When I use the code in node(v8.4.0) and safari development tool(console), it works well. That's interesting, since the sort method expects a callback returning a number, and the above expression is returning a boolean. The code is not correct or, at least, your code is not supposed to what you're expecting. Commented Nov 22, 2018 at 14:32
  • Thanks, briosheje. I thought callback of sort method can return boolean. But that's wrong. Safari console and node are weird...;( Commented Nov 22, 2018 at 14:51

1 Answer 1

7

The .sort() callback must return a number, not a boolean. The return value should be:

  • a negative number if the first element should go before the second;
  • a positive number if the first element should go after the second;
  • zero if the two elements are ordered the same.

For strings, you can use the .localeCompare() method:

arr.sort((a,b) => a.name.localeCompare(b.name));
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! But that means node and safari console are wrong(or don't follow to ECMAScript standard). Because the code is wrong, but they work well..:(
@eje well a "wrong" sort comparator can sometimes work; it depends on very specific details of the sort algorithm.
Thanks to you Pointy, I got to know something new.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.