0

I have this array of objects:

let ans = [{'a' : 5},{'d' : 3 },{'c' : 0 },{'b' : 4 }];

//Attempt to sort this
ans.sort((a,b)=>{
  return Object.keys(a)[0] > Object.keys(b)[0];
});
console.log(ans);

Shouldn't this sort function sort it? If not this how to sort this.

1
  • 1
    It is happening because after comparing keys, it is evaluating to boolean, true gets converted to 1 but false gets converted to 0 instead of -1, hence your sort function is not working correctly. Commented Jun 19, 2021 at 7:43

2 Answers 2

2

The function provided for array.sort() should return a number instead of a boolean. If a > b, then a number greater than 0 should be returned. If a < b, then a number less than 0.

let ans = [{'a' : 5},{'d' : 3 },{'c' : 0 },{'b' : 4 }];

//Attempt to sort this
console.log(ans.sort((a,b)=>{
  return Object.keys(a)[0] > Object.keys(b)[0] ? 1 : -1;
}));

Sign up to request clarification or add additional context in comments.

Comments

0

Alternatively you can use localeCompare

ans.sort((a,b)=>{
    return Object.keys(a)[0].localeCompare(Object.keys(b)[0]);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.