'Array of objects not sorted if I don't use map

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, sort doesn't work:

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source