2

I have a JavaScript Array called years with some dates and one textual item like so: [ "2017", "2018", "2019", "historic" ]

I want to sort it so that 'historic' comes first, and then the remaining numbers are sorted numerically.

The following sort function works perfectly in every browser I have tested apart from Firefox, which leaves 'historic' at the end of the array:

years.sort((a, b) => {
    if (a === 'historic') {
        return -1;
    } else {
        return a - b;
    }
});

I tried adding the following console log:

let years = [ "2017", "2018", "2019", "historic" ];
years.sort((a, b) => {
    console.log(a);
    if (a === 'historic') {
        return -1;
    } else {
        return a - b;
    }
});

Firefox outputs the following:

2017 index.js:409
2018 index.js:409
2019

Suggesting it never processes the 'historic' array element.

Ele
  • 33,468
  • 7
  • 37
  • 75
Brighty
  • 383
  • 2
  • 11
  • The elements `a` and `b` might get passed into the comparison function in any order - you only checked if `a` was `historic`, but you neglected to handle the case when `b` is. – CBroe Feb 27 '20 at 09:58

2 Answers2

2

You need a symetrically check for both elements and check if a value is 'historic'. Then return the delta of the check or the delta of the values.

var array = ["2017", "2018", "2019", "historic"];

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

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

Function sort() could be called with "historic" passed as argument b, not a.

Looks like you should use more complex comparator. Check this question - how to sort mixed numeric/alphanumeric array in javascript

I.G.
  • 370
  • 1
  • 8