Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array of objects sorted when I apply map, not without it

Sorting this array of objects works if I map the objects first:

let data = [{
    "date": "2018-07-31T00:00:00Z"
}, {
    date: undefined
}, {
    "date": "2020-07-01T00:00:00Z"
}, {
    "date": "2019-08-24T11:16:26Z"
}, {
    "date": "2011-11-19T00:00:00Z"
}]

let compare = (a, b) => {
    if (a < b) return 1;
    if (a > b) return -1;
    return 0

}

// Note: Use map first
let result = data.map(x=>x.date);
console.log(result.sort(compare))

But if I sort this array without mapping the objects first, it doesnt:

let data = [{
    "date": "2018-07-31T00:00:00Z"
}, {
    date: undefined
}, {
    "date": "2020-07-01T00:00:00Z"
}, {
    "date": "2019-08-24T11:16:26Z"
}, {
    "date": "2011-11-19T00:00:00Z"
}]

// Similar compare function just adapted
let compare = (a, b) => {
    if (a.date < b.date) return 1;
    if (a.date > b.date) return -1;
    return 0

}

// Note: No map
let result = data;
console.log(result.sort(compare))

I can’t see why this happens?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is the object where the date is undefined. In the first example (with .map()), all the values are either strings or the one undefined. As per the specification of Array.prototype.sort():

"all undefined elements are sorted to the end of the array, with no
call to compareFunction"

(MDN)

In the first example, the function is never called for the undefined value, so it is sorted last. In the second example, however, whenever you get a.date on the undefined value, you get undefined. Both if statements in the sort function then resolve to false since undefined can’t be less than or greater than a string. Therefore, 0 is continually returned for the following elements. The undefined remains in place and breaks the rest of the sorting.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading