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;
    }
);
4
  • you should search javascript not react, reference this question Commented Apr 8, 2021 at 6:52
  • Is th output of second column sorted ? All I can see that the data is arranged in random manner. Commented Apr 8, 2021 at 6:56
  • @AL-zami I asked if Django is 0 then react will sort by desc order. Before that Django will sort by desc order Commented Apr 8, 2021 at 7:00
  • stackoverflow.com/a/66959021/7924858 Commented Apr 8, 2021 at 7:13

2 Answers 2

3

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

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

Comments

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

1 Comment

Can be shortened to all_data.sort((a, b) => b.Django - a.Django || b.Rect - a.Rect);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.