简体   繁体   中英

Create a new array from 2 arrays — with conditions

I have 2 arrays that I need to join together, with some conditions.

Array 1 is an array of objects that contains user ID, usernames.

Array 2 contains other data that belongs to the user ID's in the first array. The ID in the 'sentBy' parameter matches the id in the array 1.

I've been scratching my head all night to get at this state, and I'm still scratching it to find a good solution to this problem. Any help very appreciated.

Array 1:

[ { id: 1,
    username: 'test2' },
  { id: 2,
    username: 'test3' },
  { id: 3,
    username: 'test4' } ]

Array 2:

[ { sentBy: 1,
    message: 'hey',
    createdAt: 'date' },
  { sentBy: 3,
    message: 'hey2',
    createdAt: 'date' },
  { sentBy: 1,
    message: 'hey3',
    createdAt: 'date' } ]

End result should look like:

[ 
  { 
    id: 1,
    username: 'test2',
    offlineMessages: 
    [ 
      { message: 'hey', createdAt: 'date' },
      { message: 'hey3', createdAt: 'date' }
    ] 
  },
  { 
    id: 2,
    username: 'test3',
    offlineMessages: [] 
   },
  { 
    id: 3,
    username: 'test4',
    offlineMessages: 
    [ 
      { message: 'hey2', createdAt: 'date' }
    ] 
   } 
]

Here's a solution. This will modify the users array in-place.

var users = [ { id: 759141,
    username: 'test2' },
  { id: 759142,
    username: 'test3' },
  { id: 759143,
    username: 'test4' } ];

var messages = [ { sentBy: 759141,
    message: 'hey',
    createdAt: 'date' },
  { sentBy: 759143,
    message: 'hey2',
    createdAt: 'date' },
  { sentBy: 759141,
    message: 'hey3',
    createdAt: 'date' } ];

var usersMap = {};
var user;

for (var i = 0; i < users.length; ++i) {
    user = users[i];
    usersMap[user.id] = user;
    user.offlineMessages = [];
}

for (var i = 0; i < messages.length; ++i) {
    user = usersMap[messages[i].sentBy];

    if (user) {
        user.offlineMessages.push({
            message: messages[i].message,
            createdAt: messages[i].createdAt
        });
    }
}

Try this function:

var getMessageById = function (userId) { 
    return array2.filter(function (obj) { 
        return obj.sentBy == userId; 
    }); 
};

It'll return all messages for a specific user.

I like to work with hash tables..

result = []; // -> Should be {} ! Read comments below!
for(var i in array1) {
  result[array1[i].id] = array1[i];
  result[array1[i].id].offlineMessages = [];
}

for(var i in array2) {
  result[array2[i].sendBy].offlineMessages.push( {
    message: array2[i].message,
    createdAt: array2[i].createdAt
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM