Hello fCC family
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:
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?
Not sure what first.timeOut.value
is? I guess you want to use first.timeOut
.
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??
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
1 Like
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
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.
How do I incorporate that into my object?
Here you go:
const sortByValue = myArray.sort((first, second) => {
return new Date(first.timeOut).getTime() - new Date(second.timeOut).getTime();
});
1 Like
OH!
I was thinking you meant into the array object
Thanks @BenGitter
You could do that as well, but this way you don’t have to complicate your data, only the sort function.
1 Like
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
1 Like