Tushar Shahi
Tushar Shahi

Reputation: 20616

Sort array of objects by keys not working

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.

Upvotes: 0

Views: 852

Answers (2)

Rohan B
Rohan B

Reputation: 116

Alternatively you can use localeCompare

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

Upvotes: 0

fin444
fin444

Reputation: 747

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;
}));

Upvotes: 2

Related Questions