0

I'm trying to sort an array of objects in JS, but for some reason it doesnt work :(

This is the code I'm running:

let  myArr = [{"name": "a", "age": 21}, {"name": "b", "age": 18}, {"name": "c", "age": 20}];
console.log(myArr.sort((a, b) => {
    return a["age"] > b["age"];
}))

The output is the same array as it was declared:

[
  { name: 'a', age: 21 },
  { name: 'b', age: 18 },
  { name: 'c', age: 21 }
]

When I looked it up it seemed like it's written as it should, not really sure what went wrong.

Any idea what I did wrong?

2
  • 2
    You can use - instead of >. So that's myArr.sort((a, b) => a.age - b.age). If you want the eldest first, you can use b.age - a.age. Commented Mar 29, 2021 at 10:07
  • 1
    Does this answer your question? Sorting an array of objects by property values Commented Mar 29, 2021 at 10:14

2 Answers 2

3

Use - instead of >. It should return a Number type rather than Boolean type. see sort on mdn

let myArr = [
  { name: "a", age: 21 },
  { name: "b", age: 18 },
  { name: "c", age: 20 },
];
console.log(
  myArr.sort((a, b) => {
    return a["age"] - b["age"];
  })
);

Using one-liner syntax using arrow function

let myArr = [
  { name: "a", age: 21 },
  { name: "b", age: 18 },
  { name: "c", age: 20 },
];
console.log(myArr.sort((a, b) => a.age - b.age));

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

Comments

0

Dataset

let arr = [
    { name: 'A', age: 40 },
    { name: 'B', age: 50 },
    { name: 'C', age: 30 },
]

Sort: Ascending order on age values

arr?.sort((a, b) => {
        return a?.age-b?.age
})

Sort: Descending order on age values

arr?.sort((a, b) => {
        return b?.age-a?.age
})

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.