4

How can I sort this array based upon id ?

const arr = [{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];
const sorted_by_name = arr.sort((a, b) => a.id > b.id);
console.log(sorted_by_name);

expected output

const arr = [
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];
3
  • your expected results matches ... though, I'd use a.id - b.id instead Commented Aug 11, 2021 at 6:49
  • I feel like you already did it, what is the problem? Commented Aug 11, 2021 at 6:51
  • 2
    @SeidAkhmedAgitaev OP's array is still not sorted Commented Aug 11, 2021 at 6:51

2 Answers 2

6

Much better return a.id - b.id when you order the array:

const arr = [{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];
const sorted_by_name = arr.sort((a, b) => {
   return a.id - b.id;
});
console.log(sorted_by_name);

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

Comments

2

You can directly compare using a-b, otherwise, if you're comparing the values, you need to return -1, 0 or 1 for sort to work properly

const arr = [{
    "id": 38938888,
    "subInternalUpdates": true,
  },
  {
    "id": 38938887,
    "subInternalUpdates": true
  },
  {
    "id": 38938889,
    "subInternalUpdates": true
  }
];
const sorted_by_name = arr.sort((a, b) => a.id - b.id);
console.log(sorted_by_name);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.