senty
senty

Reputation: 12847

Sorting multiple array objects with different keys

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

Upvotes: 0

Views: 75

Answers (2)

cyr_x
cyr_x

Reputation: 14257

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']));

Upvotes: 0

trincot
trincot

Reputation: 350270

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))

Upvotes: 1

Related Questions