Skip to content Skip to sidebar Skip to footer

JS - Sorting Array Of Objects

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},

Solution 1:

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

Post a Comment for "JS - Sorting Array Of Objects"