Home > Software engineering >  Merge two arrays by name value in javascript
Merge two arrays by name value in javascript

Time:05-28

var arr1 = [{name: "lang", age: "23"},{name:"shen", "age" : "18"}];
var arr2 = [{name : "shen Fajarda", status: "married"}];

How to merge this 2 arrays by name though the name in arr1 has the name shen while the arr2 has the whole name shen Fajarda.

This the output that i need,

var arr3 = [{name: "lang", age: "23"},{name:"shen", age : "18",status:"married"}];

CodePudding user response:

Just map over each item in the first item and merge with the corresponding item in the second array if they can be found.

const arr1 = [{name: "lang", age: "23"},{name: "shen", "age": "18"}];
const arr2 = [{name: "shen Fajarda", status: "married"}];

const merged = arr1.map(person => {
    const name = person.name.toLowerCase();
    const otherRecord = arr2.find(({name: candidateName}) => candidateName.toLowerCase().includes(name));

    return otherRecord ? {...person, ...otherRecord} : person;
});

CodePudding user response:

You can use reduce and inside the reduce callback check if the second array contains same name using find

let arr1 = [{
  name: "lang",
  age: "23"
}, {
  name: "shen",
  "age": "18"
}];
let arr2 = [{
  name: "shen Fajarda",
  status: "married"
}];


const mergedVal = arr1.reduce((acc, curr) => {
  const name = curr.name.toLowerCase();
  const isNameAvl = arr2.find(elem => elem.name.toLowerCase().includes(name));
  isNameAvl && acc.push({ ...curr,
    ...isNameAvl
  });
  !isNameAvl && acc.push(curr);
  return acc;
}, []);
console.log(mergedVal)

  • Related