skip to Main Content

I have this array of pairs in JS :

    var my_array = [['line_1','2'],['line_2','0'],['line_3','5'],['line_4',''],['line_5','4'],]
    
var my_sorted_array =my_array.sort((a, b) => a[1] - b[1])

console.log(my_sorted_array)

For now to sort it by second item I am using th code below

But I would like to put the blank/empty and null values to the end.

Expected result :

[['line_1','2'],['line_5','4'],['line_3','5'],['line_2','0']['line_4','']]

Thanks

2

Answers


  1. Chosen as BEST ANSWER

    I validate the Carsten Massmann answer because it's shorter and easier than mine. Thanks to him.

    Here is another way do to it that I finally found :

    var my_sorted_array = my_array.sort(function(a, b) {
        if(a[1] === "" || a[1] === null || a[1] === "0") return 1;
        if(b[1] === "" || b[1] === null || b[1] === "0") return -1;
        if(a[1] === b[1]) return 0;
        return a[1] < b[1] ? -1 : 1;});
    

  2. You could replace each 0 value with Infinity while doing the sort comparisons:

    let a = [['line_1','2'],['line_2','0'],['line_3','5'],['line_4',''],['line_5','4']];
    
    a.sort(([,a],[,b])=>(+a||Infinity)-(+b||Infinity));
    
    console.log(a);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search