Merge object in array javascript

It's been a while since this question was asked, but I thought I'd chime in as well. For functions like this that execute a basic function you'll want to use over and over, I prefer to avoid longer-written functions and loops if I can help it and develop the function as a one-liner using shallow Array.prototype functions like .map() and some other ES6+ goodies like Object.entries() and Object.fromEntries(). Combining all these, we can execute a function like this relatively easily.

First, I take in however many objects you pass to the function as a rest parameter and prepend that with an empty object we'll use to collect all the keys and values.

[{}, ...objs]

Next, I use the .map() Array prototype function paired with Object.entries() to loop through all the entries of each object, and any sub-array elements each contains and then either set the empty object's key to that value if it has not yet been declared, or I push the new values to the object key if it has been declared.

[{},...objs].map((e,i,a) => i ? Object.entries(e).map(f => (a[0][f[0]] ? a[0][f[0]].push(...([f[1]].flat())) : (a[0][f[0]] = [f[1]].flat()))) : e)[0]

Finally, to replace any single-element-arrays with their contained value, I run another .map() function on the result array using both Object.entries() and Object.fromEntries(), similar to how we did before.

let getMergedObjs = (...objs) => Object.fromEntries(Object.entries([{},...objs].map((e,i,a) => i ? Object.entries(e).map(f => (a[0][f[0]] ? a[0][f[0]].push(...([f[1]].flat())) : (a[0][f[0]] = [f[1]].flat()))) : e)[0]).map(e => e.map((f,i) => i ? (f.length > 1 ? f : f[0]) : f)));

This will leave you with the final merged object, exactly as you prescribed it.

let a = {
  a: [1,9],
  b: 1,
  c: 1
}
let b = {
  a: 2,
  b: 2
}
let c = {
  b: 3,
  c: 3,
  d: 5
}

let getMergedObjs = (...objs) => Object.fromEntries(Object.entries([{},...objs].map((e,i,a) => i ? Object.entries(e).map(f => (a[0][f[0]] ? a[0][f[0]].push(...([f[1]].flat())) : (a[0][f[0]] = [f[1]].flat()))) : e)[0]).map(e => e.map((f,i) => i ? (f.length > 1 ? f : f[0]) : f)));

getMergedObjs(a,b,c); // { a: [ 1, 9, 2 ], b: [ 1, 2, 3 ], c: [ 1, 3 ], d: 5 }

An array is a collection of elements or items. We use arrays to store data as elements and retrieve them back when we need them. The array is a data structure widely used in many programming languages, and JavaScript is not an exception.

You may need to merge one or more arrays to combine all the elements from the individual arrays into one array. We face this need when we have data coming from different streams, and we want to merge them into one data structure.

In this article, we will learn five different ways to merge arrays in JavaScript. We will also conclude which is the best way among all and when to use it.

If you like to learn from video content as well, this article is also available as a video tutorial here: 🙂

Please feel free to subscribe for the future content

Alright, let's get started.

1. Using the traditional for loop

Using the for loop to merge two or more array elements may be the most viable way. Most of us are aware of how to use for-loops in programming. So it is the easiest option to start with. However, it may not be the best solution for the problem at hand.

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array.

Here is a JavaScript function doing the same,

const merge = (first, second) => {
  for(let i=0; i<second.length; i++) {
    first.push(second[i]);
  }
  return first;
}

Now, we can call the merge() function and pass two arrays as the arguments for merging.

merge([1,2,3], [4,5,6]);

As we expected, here is the output of the merged array,

Merge object in array javascript

Alright, but how do we merge more than two arrays using the same merge() function? Well, it may not be a very friendly way but, we can do something like this,

merge(merge([1,2,3], [4,5,6]), [7,8,9]);

So here, we first merge two arrays and merge the output of it with another array.

Merge object in array javascript

As you can guess, as our requirement of the number of input arrays grows for merge, it will be a lesser friendly way to manage it. So, using the for-loop to merge two or more arrays is fine, to begin with, but may not be an excellent method to use in practice.

2. Using the Spread operator

Since ES6, we can use the ... (yes, three consecutive dots) as a spread operator to destructure arrays. We can use the spread operator on arrays within an array literal([]) to merge them. Let's see it with an example.

First, we will take two arrays, arr1 and arr2. Then merge the arrays using the spread operator(...) within an array literal.

const arr1 = [1,2,3];
const arr2 = [4,5,6];

// Merge arrays
const merged = [...arr1, ...arr2];

console.log(merged); // [1,2,3,4,5,6]
console.log(arr1); // [1,2,3]
console.log(arr2); // [4,5,6]

Now, notice the output of the merge. The arrays arr1 and arr2 are merged, and their elements are combined into a new array. Please note, the input arrays are not changed here.

Ok, so how do we merge more than two arrays using this method? Easy, pass as many arrays you want to merge as comma-separated.

const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [7,8,9];

// Merge arrays
const merged = [...arr1, ...arr2, ...arr3];

console.log(merged); // [1,2,3,4,5,6,7,8,9]

This way of merging arrays is much convenient than using the traditional for-loop approach we have seen before. It is a go-to way to merge arrays in JavaScript except for a tiny gotcha that we will see in a while!

3. Using the concat() array method

JavaScript Array object has several practical methods. One of them is the concat() method. The primary usage of the concat method is to merge two arrays.

const arr1 = [1,2,3];
const arr2 = [4,5,6];

// Merge arrays
const merged = arr1.concat(arr2);

console.log(merged); // [1,2,3,4,5,6]
console.log(arr1); // [1,2,3]
console.log(arr2); // [4,5,6]

In the above code, we merge two arrays using the concat() method. However, it is not my favorite syntax in merging arrays. We may misinterpret The syntax arr1.concat(arr2) as we are merging arr2's element into arr1 and changing the array1 array itself. That's not the fact, though.

Like we used the spread operator, the concat method will not change the input arrays. Rather, it creates a new array merging all the input arrays and returns it. So, a better way of writing the concat() method to merge arrays is,

const merged = [].concat(arr1, arr2);

Here, it is clear that we can concat multiple arrays to an empty array and return the merged array as a result. You can pass as many arrays as input arguments to the concat() method.

Great, but which one to use? The spread operator or the concat() method?

If you are sure the inputs are all arrays, please use the spread operator. It is a very straightforward and modern way to merge arrays. But if you are unsure about the input element type, use the concat() method.

For example, let's take a string tapas and use the spread operator on it with the array literals,

[...'tapas']

What do you think the output will be? The string tapas will be destructured into an array of characters it is made of,

Merge object in array javascript

So, when you merge it with other arrays, the final result may not be the one you were expecting,

const arr = [1,2,3];
const name = 'tapas';

const merged = [...arr, ...name];
console.log(merged);

The output,

Merge object in array javascript

In such cases, use the concat() method instead,

const arr = [1,2,3];
const name = 'tapas';

const merged = [].concat(arr, name);
console.log(merged);

The output,

Merge object in array javascript

4. Using the push() array method

We use the push() method to insert an element at the end of the array. We can use this method to merge two or more arrays as well. Please take a look,

const arr1 = [1,2,3];
const arr2 = [4,5,6];

// Merge arrays
const merged = arr1.push(...arr2);

console.log(merged); // 6
console.log(arr1); // [1,2,3,4,5,6]
console.log(arr2); // [4,5,6]

A few essential points to note here,

  • The push() method inserts an element into an array. The method changes the array and returns the number of elements of the array after insertion. So, in the example above, the first array, arr1, will be changed to accommodate the new elements. The return value is 6 from the push() method is assigned to the merged variable.
  • We must spread the array while pushing its element to the other array, arr1.push(...arr2). Missing the spread operator will insert the entire array to the other array,

    const arr1 = [1,2,3];
    const arr2 = [4,5,6];
    
    // Merging without the ... on arr2
    const merged = arr1.push(arr2);
    
    console.log(merged); // 4
    console.log(arr1); // [1,2,3,[4,5,6]]
    console.log(arr2); // [4,5,6]
    

So, how do we merge more than two arrays using the push() method? Here it is,

const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [7,8,9];

// Merge more than two arrays
arr1.push(...[...arr2, ...arr3]); // [1,2,3,4,5,6,7,8,9]

5. Using the reduce() array method

The last way to merge multiple arrays is using the reduce() method.

This way of merging array is not recommended as it is closer to the for-loop approach we have seen above with the extra headache of reduce. We are discussing it here for the sake of building awareness!

With the reduce method, we can initialize a variable(arr) with the value of arr1 and then insert the elements of arr2 one by one to arr.

const arr1 = [1,2,3];
const arr2 = [4,5,6];

const merged = arr2.reduce((arr, item) => {
    arr.push(item);
    return arr;    
}, arr1);

console.log(merged);

The output,

Merge object in array javascript

In Summary

To Summarize,

  • There are more than a couple of ways to merge two or more arrays into one in JavaScript.
  • Using the spread operator or the concat() method is the most optimal solution.
  • If you are sure that all inputs to merge are arrays, use spread operator. In case you are unsure, use the concat() method.
  • You can use the push() method to merge arrays when you want to change one of the input arrays to merge.
  • Using the reduce() method to merge arrays is a bit of overhead.

Do you know any other ways to merge arrays in JavaScript? Please feel free to let us know in the comment section below.

You can find all the source code used in this article from my GitHub repo,


I hope you found the article insightful and informative. Please like/share so that it reaches others as well.

Let's connect. I share my learnings on JavaScript, Web Development, and Blogging on these platforms as well,

  • Follow me on Twitter
  • Subscribe to my YouTube Channel

How do you combine objects in arrays?

5 ways to merge arrays in JavaScript and their differences. You may need to merge one or more arrays in JavaScript. ... .
Using the traditional for loop. ... .
Using the Spread operator. ... .
Using the concat() array method. ... .
Using the push() array method. ... .
Using the reduce() array method..

How do I merge two objects in JavaScript?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

Can we merge two objects in JavaScript?

To merge two objects in JavaScript, you can use the spread ... operator. The spread operator creates a new object with all the properties from the first and second object. If there's two properties with the same name, the property from the second object wins out.

How do I merge one array to another in JavaScript?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.