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?

8
  • Can you define what you mean by "special" characters? And how do you want the special ones ordered? Thx. Commented Apr 4, 2018 at 7:16
  • I have only "-" as a character which need to come in last. Commented Apr 4, 2018 at 7:17
  • If "-" is the only non-numerical character then you can just do arr.sort(function(a,b) { return b - a }); Commented Apr 4, 2018 at 7:19
  • 4
    wrong dupe target, because it does not answer the question of not a number items for sorting. Commented Apr 4, 2018 at 7:19
  • @NinaScholz: Then change the target to a proper one. I'm sure it exists. Commented Apr 4, 2018 at 7:26

1 Answer 1

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

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

3 Comments

It works-- var array = [5, 3, 10, "-", 2, "-"]; array.sort((a, b) => isNaN(a) - isNaN(b) || b - a); Thanks @Nina
Nice. One of those cases in which arithmetic-on-booleans-as-integers work pretty well.
So, instead of closing obvious duplicates, you're still answering them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.