0

Before, I was combining 2 arrays into one array and using sort(), I was able to sort them by created_at.

let result = [...item.messages, ...item.chat_messages]
result.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
item.messages = result

Now, I am in another scenario. I want to add one more array (sms_messages) into this array and however want it to order by its scheduled_at field.

Is it possible to achieve it with this approach?

let result = [...item.messages, ...item.chat_messages, ...item.sms_messages]
// and order by messages' and chat_messages' created_at (like above) together as 
// sms_messages' sheduled_at
3
  • Does only sms has the scheduled_at prop? Commented Oct 14, 2017 at 17:33
  • @OriDrori, yes. Others should use created_at like before but sms needs to use scheduled_at. So I can give a list in related order Commented Oct 14, 2017 at 17:34
  • Please provide an actual complete example of the data structure you want to work with. It's hard to discern from your description. Commented Oct 14, 2017 at 17:39

2 Answers 2

1

You could use || to get the first of both properties it finds to be there, assuming that each object has at least one of both properties, but scheduled_at gets precedence:

result.sort((a, b) => 
    new Date(b.scheduled_at || b.created_at) - new Date(a.scheduled_at || a.created_at))
Sign up to request clarification or add additional context in comments.

3 Comments

That seems like a good approach, however sms has created_at property as well as scheduled_at and I think it is ordering by created_at rather than scheduled at
That should not be the case: scheduled_at is taken if it exists before falling back to created_at. If an object has both properties, scheduled_at will be used.
Yes, I am sorry. It is working like charm! Thanks a million
0

Just check which which property exists and use it to sort the objects.

const sortByDate = props => {
  return (a, b) => {
    let propA = props.find(p => a.hasOwnProperty(p));
    let propB = props.find(p => b.hasOwnProperty(p));
    if(!propA || !propB) return 0;
    return new Date(b[propB]) - new Date(a[propA]);
  };
}

result.sort(sortByDate(['scheduled_at', 'created_at']));

2 Comments

But sms_messages has both properties scheduled_at and created_at. I think this won't solve this because of it
In my example it prioritises the scheduled_at attribute and then falls back to created_at. So if scheduled_at is present on the object it will get sorted by sheduled_at.

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.