How to join two arrays of objects into one with JavaScript
Joining two arrays may sound like an easy task yet looking, for example, at this StackOverflow question and the number of answers (let’s note that none was accepted up to this day!) it may cause a bit of headache.
While we can use external libraries to join arrays, we can simply rely on plain JavaScript. In this article we are going to look how to do it with plain JS and also with the newer ES6 syntax.
First of all let’s define the problem.
We have two arrays abc
and def
. We want to join them together into one, single array with all the elements present:
const abc = ['a', 'b', 'c'];
const def = ['d', 'e', 'f'];
// expected result: ['a', 'b', 'c', 'd', 'e', 'f']
Plain JavaScript
We can achieve that easily with plain javascript and Array.prototype.concat()
method:
const result = abc.concat(def);
console.log(result);
// outputs: ['a', 'b', 'c', 'd', 'e', 'f']
Let’s try the same with array of objects:
const a = [{id: 1}, {id: 2}];
const b = [{id: 3}, {id: 4}];
// expected result: [{id: 1}, {id: 2}, {id: 3}, {id: 4}]const result = a.concat(b);
console.log(result);
// outputs: [{id: 1}…