-3

i have two array and i want merge two arrays but array 1 merge with 2 and create new array also have array1 and array2 data in new array but not duplicate entries.

i tried using the concat function but it's not useful

Array 1:

[[id: 45,
    name: Tv,
    active: false,
], [id: 56,
    name: Car,
    active: true,
][id: 60,
    name: bus,
    active: false,
]]

Array 2:

[[id: 45,
        company: sony,
        size: 32,
        price: 451
    ],
    [id: 56,
        company: suzuki,
        size: L,
        price: 3000
    ]]

i want data like that:

[[id: 45,
        name: tv,
        active: false,
        company: sony,
        size: 32,
        price: 451
    ],
    [id: 56,
        name: car,
        active: true,
        company: suzuki,
        size: M,
        price: 3000
    ],
    id: 60,
    name: bus,
    active: false]]

but if you are create object in object in javascript using this data

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84

1 Answers1

1

You can use the following approach in order to merge arbitrary number of arrays:

  • Merge all the items into a single array
  • Get an array of unique ids
  • Merge all the objects with the same ids

const arr1 = [{ id: 45, name: "Tv", active: false }, { id: 56, name: "Car", active: true }, {id: 60, name: "bus", active: false }];
const arr2 = [{ id: 45, company: "sony", size: 32, price: 451 }, { id: 56, company: "suzuki", size: "L", price:3000 }];
const arr3 = [{ id: 45, type: 'electronics' }];

const mergeArrays = (...arrays) => {
  const all = [].concat.apply([], arrays);
  const ids = new Set(all.map(item => item.id));
  return Array.from(ids).map(id =>
    Object.assign({}, ...all.filter(item => item.id === id))
  );
};

console.log(mergeArrays(arr1, arr2, arr3));
antonku
  • 7,377
  • 2
  • 15
  • 21