2

I have two columns of value. If the first column any value becomes 0 then sort by another column value.

Probable input

Django      Rect
10          20
20          11
1           100
100         1
0           1
0           100
0           9
0           0
0           0

Expected out

Django      Rect
100         1
20          11
10          20
1           100
0           100
0           9
0           1
0           0
0           0

I would expect descending order sort. I can sort for any of one column but I need to sort at a time two-column according to the given condition. I have tried so far

all_data.sort(function(a,b){
      return a.Django- b.Django;
    }
);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
mhhabib
  • 2,975
  • 1
  • 15
  • 29

2 Answers2

2

Your issue looks like this: "The ordinal property you want to sort by".

To be more precise, when you should sort Django and Rect.

const all_data = [{Django:10,Rect:20},{Django:20,Rect:11},{Django:1,Rect:100},{Django:100,Rect:1},{Django:0,Rect:1},{Django:0,Rect:100},{Django:0,Rect:9},{Django:0,Rect:0},{Django:0,Rect:0}];

all_data.sort((a, b) => b.Django - a.Django || b.Rect - a.Rect);
console.log(all_data);

Explain:

Firstly, sort desc by Django. Secondly, if Django is the same, then will sort desc by Rect

Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
-1

You say that you only want to sort by Rect when Django is 0. However, it seems to me that it's better to sort by Rect in all cases where a.Django === b.Django.

You can check for equality in your compare function.

all_data.sort(function(a,b) {
        if (a.Django === b.Django) {
            return a.Rect - b.Rect;
        }
        return a.Django- b.Django;
    }
);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
super
  • 12,335
  • 2
  • 19
  • 29