Roster
Roster

Reputation: 1944

Simple array of objects sort is not working properly

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

Upvotes: 1

Views: 112

Answers (1)

Andrew Ymaz
Andrew Ymaz

Reputation: 2203

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.

Upvotes: 3

Related Questions