4

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

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

I want this to sort with numeric values followed by all the "-" characters.

Required result:-

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

What i have 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 this in single iteration?

Abhishek Agarwal
  • 165
  • 1
  • 2
  • 13

1 Answers1

2

You could check for NaN and move this items to the end.

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

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

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392