1

I have an array that contains two different kinds of objects, each with their own date field in which the key is different. See below:

const array = [
  { id: 1, occurs_at: '2017-02-03T07:00:01.000Z' },
  { id: 2, occurs_at: '2017-02-03T10:00:01.000Z' },
  { id: 3, start: '2017-02-03T04:00:01.000Z' },
  { id: 4, start: '2017-02-03T06:00:01.000Z' },
];

I'm trying to get them in ascending order, but I can't seem to find the solution. I've been using Lodash for other sorting based on a single property. Any thoughts?

6
  • Is there a way to know which key it'll be? Are there more than two different date keys? Or are 'occurs_at' and 'start' the only two possible date keys? Do the objects have more keys apart from the date and the id? Commented Feb 28, 2017 at 15:24
  • start and occurs_at are the only possible keys for the date? Commented Feb 28, 2017 at 15:24
  • @baao correct. Those would be the only possible keys. Commented Feb 28, 2017 at 15:24
  • Edit additional details into your question. Comments are for us to ask for clarifications. Commented Feb 28, 2017 at 15:24
  • Then Nina has answered your question... :-) Commented Feb 28, 2017 at 15:25

3 Answers 3

5

You could test for the wanted property and use only ones with a truthy value.

var array = [{ id: 1, occurs_at: '2017-02-03T07:00:01.000Z' }, { id: 2, occurs_at: '2017-02-03T10:00:01.000Z' }, { id: 3, start: '2017-02-03T04:00:01.000Z' }, { id: 4, start: '2017-02-03T06:00:01.000Z' }];

array.sort(function (a, b) {
    return (a.occurs_at || a.start).localeCompare(b.occurs_at || b.start);
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

I would use sortBy() and pick():

const sorted = _.sortBy(array, i => new Date(
  _(i)
    .pick(['occurs_at', 'start'])
    .values()
    .first()
));

If you know that the each collection item is going to have either an occurs_at or a start property that's a date string, you can use pick() to get both. Obviously only one exists, so this will return an object with the correct value.

At this point, you no longer care about the key, since you know that its an object with a single date value. So you get it using values() and first().

Comments

-3
array.sort(function(a, b) {
    return new Date(b.occurs_at) - new Date(a.occurs_at);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.