javascriptarrayssortingnull

JS sort array of pair with null and empty values at the end


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


Solution

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