Home > Software design >  How to compare two array and create new one with different key value pair?
How to compare two array and create new one with different key value pair?

Time:07-15

I have two array and need to take specific key value pair and assign to third one array and it will also take care of duplication entry.

First Array :

[ 
  {id: 2, name: "HSBC", status: "YES"},
  {id: 3, name: "Morgan Stanley", status: "Pending"}
]

Second Array:

[
   {id: 1, name: "Deutsche Bank", category: "EQUITIES"},
   {id: 2, name: "HSBC", category: "EQUITIES"},
   {id: 3, name: "Morgan Stanley", category: "EQUITIES"},
   {id: 4, name: "Credit Suisse", category: "EQUITIES"},
]

From above two arrays I need to take name and status field and create the new array. Like below:

[
  { brokerName: "HSBC", statis: "YES"},
  { brokerName: "Morgan Stanley", statis: "Pending"},
  { brokerName: "Deutsche Bank", statis: ""},
  { brokerName: "Credit Suisse", statis: ""},
]

TIA. Stackblitz

CodePudding user response:

let arr1 = [{id: 1, name: "name", status: "YES"}];
let arr2 = [{id: 1, name: "name", category: "EQUITIES"}];
let sumbit = [];

for (let i=0; i<arr1.length; i  ) {
    let is_there = false;
    for (let j=0; j<arr2.length; j  ) {
        if (arr1[i].name == arr[j].name) {
            submit.push({brokerName: arr1[i].name, statis: arr1[i].status});
            is_there = true;
        }
    }
    if (!is_there) submit.push({brokerName: arr1[i].name, statis: ""})
}

You could just write the code :D

CodePudding user response:

Here is an example:

const array1 = [ 
  {id: 2, name: "HSBC", status: "YES"},
  {id: 3, name: "Morgan Stanley", status: "Pending"}
];
const array2 = [
   {id: 1, name: "Deutsche Bank", category: "EQUITIES"},
   {id: 2, name: "HSBC", category: "EQUITIES"},
   {id: 3, name: "Morgan Stanley", category: "EQUITIES"},
   {id: 4, name: "Credit Suisse", category: "EQUITIES"},
];

// returns { name, status } recoreds from any number of arrays
function getBrokersDataFromArrays(...arrays) {
  const allBrokers = new Map();
  // collect all the available data for all the brokers
  arrays.flat().forEach(broker => {
    if (allBrokers.has(broker.name)) {
      allBrokers.set(broker.name, { ...allBrokers.get(broker.name), ...broker });
    } else {
      allBrokers.set(broker.name, broker);
    }
  });
  // return only { name, status } fields from the collected brokers
  return Array.from(allBrokers.values()).map(broker => (
    { name: broker.name, status: broker.status }
  ));
}

const brokersData = getBrokersDataFromArrays(array1, array2);

console.log(brokersData);

  • Related