-2

I have two arrays:

First array:

generalInfo = [{"fName": "Suku", "lName": "Brown", "sex": "Male", "Id": "RY12S"}, {"fName": "Mary", "lName": "Sue", "sex": "Female", "Id": "UT72W"}]

Second array:

paymentInfo = [{"Id": "RY12S", "amount": "1000.00", "purpose": "rent", "date": "2017-17-07"}, {"Id": "UT72W", "amount": "5000.00", "purpose": "renovation", "date": "2017-15-07"}]

Now, I want to be able to compare the Id field for the both arrays and return their unique information.

At least the third should look like this:

specificInfo = [{"Id": "RY12S","fName": "Suku", "lName": "Brown", "amount": "1000.00", "purpose": "rent"}, {"Id": "UT72W","fName": "Mary", "lName": "Sue", "amount": "5000.00", "purpose": "renovation"}]

Is there any easy way to achieve this?

Israel Z Kollie
  • 273
  • 5
  • 17

1 Answers1

0

An ES6 solution with map and find:

var generalInfo = [{"fName": "Suku", "lName": "Brown", "sex": "Male", "Id": "RY12S"}, {"fName": "Mary", "lName": "Sue", "sex": "Female", "Id": "UT72W"}];

var paymentInfo = [{"Id": "RY12S", "amount": "1000.00", "purpose": "rent", "date": "2017-17-07"}, {"Id": "UT72W", "amount": "5000.00", "purpose": "renovation", "date": "2017-15-07"}];

var uniqueInfo = generalInfo.map((generalItem) => {
  var paymentItem = paymentInfo.find((item) => item.Id === generalItem.Id);

  return {
    Id: generalItem.Id,
    fName: generalItem.fName,
    lName: generalItem.lName,
    amount: paymentItem.amount,
    purpose: paymentItem.purpose
  };
});

console.log(uniqueInfo);

Try to understand the logic behind this and, if you need to implement in ES5, try to do by yourself before posting here.

Alberto Trindade Tavares
  • 10,056
  • 5
  • 38
  • 46