Sorting an array with characters in Javascript

I am sorting an array with numeric values ​​and "-" as characters. My array

var arr = [5, 3, 10, "-", 2, "-"]

I want this to be sorted with numeric values ​​followed by all the "-" characters.

Required Result: -

final array = [10, 5, 3, 2, "-", "-"]

What I tried: -

var array_with_chars= arr.filter(function( element ) {
    return element.name == '-';
});
var array_with_nums= arr_obj.filter(function( element ) {
    return element.name !== '-';
});

array_with_nums.sort(function(a, b) {
  return b.name - a.name;
});

for(var i = 0; i< array_with_chars.length; i++){
    array_with_nums.push(array_with_chars[i])
}

Is there any good way to sort in a single iteration?

+4
source share
1 answer

You can check NaNand move these items to the end.

var array = [5, 3, 10, "-", 2, "-"];

array.sort((a, b) => isNaN(a) - isNaN(b) || b - a);

console.log(array);
Run codeHide result
+2
source

Source: https://habr.com/ru/post/1695739/


All Articles