Adam K Dean

Sorting objects with undefined values

Published on 12 March 2020 at 14:46 by Adam

So take a look at this:

const a = { id: 'a', timestamp: 1570790874500 }
const b = { id: 'b' }

You may have some data like this at some point, and you might try a comparison thinking that a defined value will always be higher and truthier than an undefined one.

You might try and sort them, expecting the undefined timestamps to fall to the bottom. But they won't.

> const c = [b, a]
> c.sort((i, j) => i.timestamp > j.timestamp)

(2) [{…}, {…}]
  0: {id: "b"}
  1: {id: "a", timestamp: 1570790874500}

Let's take a look at some comparisons which don't really help us.

> undefined > 1570790874500

false

> 1570790874500 > undefined

false

The best thing to do in this situation is to check the existence of the timestamp field within the sort predicate and only compare the values when the field exists. Depending on whether you want the objects with the undefined field first or last, you change which object you check for timestamp and return true when they are undefined.

Let's create some data.

> const list = [
    { id: 'a', timestamp: 1535090874500 },
    { id: 'b' },
    { id: 'c' },
    { id: 'd', timestamp: 1570790874500 },
    { id: 'e', timestamp: 1510790874500 }
  ]

So for undefined last, you check the first object passed in.

> list.sort((a, b) => !!a.timestamp ? a.timestamp > b.timestamp : true)

[ { id: 'e', timestamp: 1510790874500 },
  { id: 'a', timestamp: 1535090874500 },
  { id: 'd', timestamp: 1570790874500 },
  { id: 'c' },
  { id: 'b' } ]

And for undefined first, you check the second object passed in.

> list.sort((a, b) => !!b.timestamp ? a.timestamp > b.timestamp : true)

[ { id: 'b' },
  { id: 'c' },
  { id: 'e', timestamp: 1510790874500 },
  { id: 'a', timestamp: 1535090874500 },
  { id: 'd', timestamp: 1570790874500 } ]

And of course, the comparison here, a.timestamp > b.timestamp defines the sort order of the objects where the field is present.



This post was first published on 12 March 2020 at 14:46. It was filed under archive with tags javascript, weird.