1

Array is not sorting properly. I am sorting the objects based on id , I have written in correct way only

but it is not sorting at all.

 list = list.sort((item1, item2) => {
        return item1.id > item2.id ? 1 : -1;
      });

the sample array of objects are like this

0: {baseCalendar: {…}, id: "0"}
1: {baseCalendar: {…}, id: "1"}
2: {baseCalendar: {…}, id: "10"}
3: {baseCalendar: {…}, id: "11"}
4: {baseCalendar: {…}, id: "12"}
5: {baseCalendar: {…}, id: "2"}
6: {baseCalendar: {…}, id: "4"}
7: {baseCalendar: {…}, id: "5"}
2
  • 5
    use parseInt(). Also comparisons should return -1, 0, or 1. Commented Apr 19, 2021 at 13:03
  • 1
    In case the first comment is not clear enough: you're sorting strings instead of integers Commented Apr 19, 2021 at 13:04

1 Answer 1

3

The issue is that your ids are Strings, not Numbers, but you are comparing them as Numbers.

You have to convert them to Numbers, while you are comparing them, for examples as:

list.sort((item1, item2) => { return +item1.id > +item2.id ? 1 : -1; });

Or using parseInt(item1.id, 10) and parseInt(item2.id, 10) as proposed above.

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

1 Comment

could be just list.sort((item1, item2) => item1.id - item2.id)

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.