Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge three different arrays by comparing with id? in Angular 6

Arrays:

 array1 = [{id:1, name:"raju"},{id:2, name:"ravi"},{id:4, name:"john"},{id:6, name:"jack"}];
 array2= [{id:1, degree:"b.com"},{id:3, degree:"b.a"},{id:4, degree:"c.a"},{id:5, degree:"horticulture"}];
 array3= [{id:1, age:20},{id:3, age:21},{id:6, age:27},{id:7, age:25}];

Required result is:

resultarray = [
    {id:1, name: "raju", degree:"b.com",age:20},
    {id:2, name: "ravi"},
    {id:3, degree:"b.a", age:21},
    {id:4, name:"john", degree:"c.a"},
    {id:5, degree:"horticulture"},
    {id:6, name:"jack", age:27},
    {id:7, age:25}
 ] 

i have tried different functions and tried for two arrays but not able to merge the object which doesnt have id to compare..

like image 765
Phani Kumar Devu Avatar asked Dec 01 '25 04:12

Phani Kumar Devu


2 Answers

You can use reduce and destructuring

Here idea is

  • First merge all the arrays in one array.
  • Now using reduce we create id as key in op object
  • If id key is already there we merge the inp and op[inp.id]
  • If id is not there we create a new key with value inp

let array1 = [{id:1, name:"raju"},{id:2, name:"ravi"},{id:4, name:"john"},{id:6, name:"jack"}];
let array2= [{id:1, degree:"b.com"},{id:3, degree:"b.a"},{id:4, degree:"c.a"},{id:5, degree:"horticulture"}];
let array3= [{id:1, age:20},{id:3, age:21},{id:6, age:27},{id:7, age:25}];

let temp = [...array1,...array2,...array3]

let op = temp.reduce((op,inp)=>{
  op[inp.id] = op[inp.id] || inp
  op[inp.id] = {...op[inp.id],...inp}
  return op
},{})

console.log(Object.values(op))
like image 171
Code Maniac Avatar answered Dec 02 '25 17:12

Code Maniac


a possible solution:

let array1 = [{id:1, name:"raju"},{id:2, name:"ravi"},{id:4, name:"john"},{id:6, name:"jack"}];
let array2= [{id:1, degree:"b.com"},{id:3, degree:"b.a"},{id:4, degree:"c.a"},{id:5, degree:"horticulture"}];
let array3= [{id:1, age:20},{id:3, age:21},{id:6, age:27},{id:7, age:25}];

let resp = [].concat(array1, array2, array3).reduce((acc, ele) => {
        let obj = acc.find(x => x.id === ele.id);
        return obj ? (Object.keys(ele).forEach(x => obj[x] = ele[x]), acc) : acc.concat(ele);
    }, [])
    
console.log(resp)
like image 38
guijob Avatar answered Dec 02 '25 18:12

guijob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!