Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!