DEV Community

Cover image for Sorting objects with undefined values
Adam K Dean
Adam K Dean

Posted on

Sorting objects with undefined values

So take a look at this:

const a = { id: 'a', timestamp: 1570790874500 }
const b = { id: 'b' }
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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

> undefined > 1570790874500

false

> 1570790874500 > undefined

false
Enter fullscreen mode Exit fullscreen mode

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 }
  ]
Enter fullscreen mode Exit fullscreen mode

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' } ]
Enter fullscreen mode Exit fullscreen mode

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 } ]
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
agustinacassi profile image
Tini Cassi

It helped me, thnks!!!