Sort on iso date

Sort on iso date
0

#1

Hello fCC family :heart:

I have an array object I want to sort on an ISODate field that is stored as a string in the object, it looks like this:

const myArray = [
  {
    firstKey: 'this one last',
    timeIn: '2017-11-23T07:17:59.468Z',
    timeOut: '2017-11-23T07:36:59.469Z',
  },
  {
    firstKey: 'this one third',
    timeIn: '2017-11-23T07:17:59.600Z',
    timeOut: '2017-11-23T07:28:59.600Z',
  },
  {
    firstKey: 'this one first',
    timeIn: '2017-11-23T07:18:01.089Z',
    timeOut: '2017-11-23T07:22:01.089Z',
  },
  {
    firstKey: 'this one second',
    timeIn: '2017-11-23T07:18:00.497Z',
    timeOut: '2017-11-23T07:26:00.497Z',
  }
]

const sortByValue = myArray.sort((first, second) => {
  return second.timeOut.value - first.timeOut.value
});

console.log(sortByValue)

Here’s is the output:
image

I want to be able to sort on the timeOut key.

It doesn’t seem to make any difference which way I put the first.timeOut and second.timeOut I was hoping to be able to sort on that field…

Can it be done?


#2

Not sure what first.timeOut.value is? I guess you want to use first.timeOut.


#3

It’s the two values being sorted (first, second) it’s how you sort an array, then you minus one from the other to sort them

but in this case it doesn’t work, I’m guessing because it’s a string??


#4

What I meant is that first.timeOut does not have a property called value, so first.timeOut.value does not exist (undefined).

EDIT:
But that is not the problem. The problem is indeed that you are working with date-strings. You can solve this by:

  • Parsing the string to a Date
  • Use getTime() on that Date object => returns an integer
  • Compare those values

#5

Cool!

So it’s

  {
    firstKey: 'this one last',
    timeIn: getTime('2017-11-23T07:17:59.468Z'),
    timeOut: getTime('2017-11-23T07:36:59.469Z'),
  },

Like that?

I’ll try


#6

No, you first have to parse it to a Date object:

let dateString = '2017-11-23T07:26:00.497Z';
let dateObj = new Date(dateString);

And then you can use all Date functions, like getTime() on that object.


#7

How do I incorporate that into my object? :upside_down_face:


#8

Here you go:

const sortByValue = myArray.sort((first, second) => {
  return new Date(first.timeOut).getTime() - new Date(second.timeOut).getTime();
});

#9

OH! :upside_down_face:

I was thinking you meant into the array object :blush:

Thanks @BenGitter :+1:


#10

You could do that as well, but this way you don’t have to complicate your data, only the sort function.


#11

I really do overthink things a lot, thanks for the help @BenGitter, I’d like to think I was ~75% done, thanks for that last little bit my friend :tada: