Skip to content
Advertisement

How to join two array conditionally based on the date in javascript

I have two arrays of users which have the same iDs. I want to merge them based on the updatedAt property that each user has. The user who has newer updatedAt property has priority.

const users1 = [
    { id: 1, name: 'user1', childUsers: [2], updatedAt: '2022-02-23T00:00:00.000Z' },
    { id: 2, name: 'user2', childUsers: [3, 4], updatedAt: '2022-01-26T00:00:00.000Z' },
    { id: 3, name: 'user3', childUsers: [2, 3], updatedAt: '2022-02-24T00:00:00.000Z' },
    { id: 4, name: 'user4', childUsers: [2, 4], updatedAt: '2022-02-26T00:00:00.000Z' },
  ]
const users2 = [
    { id: 1, name: 'user1', childUsers: [2], updatedAt: '2022-02-26T00:00:00.000Z' },
    { id: 2, name: 'user2.1', childUsers: [3, 4], updatedAt: '2022-02-27T00:00:00.000Z' },
    { id: 3, name: 'user3', childUsers: [2, 3], updatedAt: '2022-02-26T00:00:00.000Z' },
    { id: 4, name: 'user4.1', childUsers: [2, 4], updatedAt: '2022-02-27T00:00:00.000Z' },
  ]

Output should be

const mergedUsers = [
{ id: 1, name: 'user1', childUsers: [2], updatedAt: '2022-02-26T00:00:00.000Z' },
{ id: 2, name: 'user2.1', childUsers: [3, 4], updatedAt: '2022-02-27T00:00:00.000Z' },
{ id: 3, name: 'user3', childUsers: [2, 3], updatedAt: '2022-02-26T00:00:00.000Z' },
{ id: 4, name: 'user4.1', childUsers: [2, 4], updatedAt: '2022-02-27T00:00:00.000Z' },

]

Advertisement

Answer

You can use Array.reduce() to group users by id, replacing any entry with a newer updatedAt property.

Once we have the grouped users, we can use Object.values() to get the desired result:

const users1 = [
    { id: 1, name: 'user1', childUsers: [2], updatedAt: '2022-02-23T00:00:00.000Z' },
    { id: 2, name: 'user2', childUsers: [3, 4], updatedAt: '2022-01-26T00:00:00.000Z' },
    { id: 3, name: 'user3', childUsers: [2, 3], updatedAt: '2022-02-24T00:00:00.000Z' },
    { id: 4, name: 'user4', childUsers: [2, 4], updatedAt: '2022-02-26T00:00:00.000Z' },
  ]

const users2 = [
    { id: 1, name: 'user1', childUsers: [2], updatedAt: '2022-02-26T00:00:00.000Z' },
    { id: 2, name: 'user2.1', childUsers: [3, 4], updatedAt: '2022-02-27T00:00:00.000Z' },
    { id: 3, name: 'user3', childUsers: [2, 3], updatedAt: '2022-02-26T00:00:00.000Z' },
    { id: 4, name: 'user4.1', childUsers: [2, 4], updatedAt: '2022-02-27T00:00:00.000Z' },
  ]

const result = Object.values([...users1, ...users2].reduce((acc, user) => { 
    // Entry either does not exist or has an older updatedAt property
    if (!acc[user.id] || (user.updatedAt > acc[user.id].updatedAt)) {
        acc[user.id] = user;
    }
    return acc;
}, {}))

console.log('Result:', result)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement