Javascript array merge all

How to Merge Arrays in JavaScript (5 Easy Ways)

In JavaScript, one of the fundamental data types is the array. Array is a collection of elements, such as numbers, strings, or other types of objects. It’s a data store that lets you store and access data easily in your JavaScript programs.

Because every program deals with data, you need arrays all the time.

One common necessity when dealing with arrays is the ability to merge one or arrays together to combine data.

This guide teaches you 5 different approaches to merging arrays in JavaScript. Besides, you will learn what is the best and worst way to do it.

1. The for Loop Approach

The first thing that comes to mind when merging arrays is a for loop.

The idea is to loop through the elements of both arrays and push them into the new merged array one by one. You can do this with two for loops.

For example, let’s merge arrays arr1 and arr2 into a new array called result:

let arr1 = [1, 2, 3] let arr2 = [4, 5, 6] let result = [] for (elem of arr1) < result.push(elem) >for (elem of arr2) < result.push(elem) >console.log(result)

This is a hard-coded way to merge two arrays. But if you want to use the loop approach more than once, then you should create a function for merging arrays.

Here’s a function merge() that takes two arrays and results the merged arrays:

const merge = (arr1, arr2) => < for (elem of arr2) < arr1.push(elem) >return arr1 > // Example use let arr1 = [1, 2, 3] let arr2 = [4, 5, 6] let merged = merge(arr1, arr2) console.log(merged)

This function works such that:

  1. It takes two arrays arr1 and arr2 as arguments.
  2. It loops through the second array and adds each element to the arr1.
  3. It then returns the arr1 with both the original arr1 elements and the arr2 elements.

Notice that this function does not modify the original array arr1. Instead, it takes a copy of the input arrays and returns a new array.

Now, let’s think about the practicality of this approach to merging arrays. If there’s more than two arrays to merge, the code gets complicated. You’d have to do something like:

merge(merge(merge(arr1, arr2), arr3), arr4)

Also, having to implement the merging functionality seems redundant. It’s such a common operation there must be better ways to do it.

This leads to the second approach.

2. The Spread Operator (…)

As of ES6, it’s been possible to use the three dots spread operator (…) to pull apart values from arrays and JavaScript objects.

Thanks to the spread operator, merging arrays is much easier with a convenient syntax.

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

Here’s an illustration of how the spread operator works in the above code example:

Читайте также:  Примеры разметка html таблица

Merge two arrays with the spread operator

The spread operator takes a copy of each value from the arrays and places them into the merged array.

This also highlights the fact that the original arrays remain untouched.

The cool part in using hte spread operator is that you’re not limited to two arrays. You can merge as many arrays as you like. Also, the arrays don’t need to be of the same size.

For example, let’s combine three arrays:

let arr1 = [1, 2, 3] let arr2 = [4, 5, 6] let arr3 = [7, 8, 9, 10] let merged = [. arr1, . arr2, . arr3] console.log(merged)

The spread operator approach is much more convenient approach to merging the arrays than the traditional for loop approach you saw earlier.

3. The concat() Method

In JavaScript, the array data type comes with a bunch of native methods. These methods help developers deal with arrays in a streamlined fashion.

One of the built-in array methods in JavaScript is the concat() method. You can call this method on any JavaScript array and pass it another array as an argument. This method call creates a new array that merges the two arrays.

For example, let’s merge two arrays arr1 and arr2:

let arr1 = [1, 2, 3] let arr2 = [4, 5, 6] let merged = arr1.concat(arr2) console.log(merged)

This is a pretty straightforward way to merge arrays in JavaScript. The only problem is in the syntax. Please, take a look at this line of code:

Doesn’t it look like you’re adding the elements of arr2 to arr1 and thus modify arr1?

Because this is what it does NOT do!

Instead, the above line of code creates a new merged array with the contents of arr1 and arr2.

If you prefer to use the concat() method, a much cleaner way to call it is by calling it on an empty array and passing the two arrays as arguments:

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

When you look at this solution, its much easier to see you’re merging two arrays into an empty array to create a new one.

4. The push() Method

Another popular array method in JavaScript is the push() method.

The push() method pushes any number of argument values to the original array. In other words, this method modifies the original array unlike other approaches you’ve seen so far.

In the very first example, you already saw how to use the push() method to push elements to an array one by one.

But the push() method can take an arbitrary number of arguments.

You also learned you can use the spread operator (…) to pull apart values from an array. So you can use the spread operator to give the push() method all the array elements as arguments.

For instance, let’s add the arr2 elements to the arr1:

let arr1 = [1, 2, 3] let arr2 = [4, 5, 6] arr1.push(. arr2) console.log(arr1)

5. The reduce() Method

The last approach to merging arrays is by using the reduce() method.

The idea of the reduce() function is to implement what’s called folding in maths. Typically, you reduce an array into a single value, such as the sum or the product of the elements. But you can also use the reduce() method to merge two arrays.

For example, let’s merge arr1 and arr2 by adding the arr2 elements to the end of arr1:

let arr1 = [1, 2, 3] let arr2 = [4, 5, 6] arr2.reduce((arr, item) => < arr.push(item); return arr; >, arr1) console.log(arr1)

The above code works such that it takes each element of arr2 and pushes it to arr1. This approach is very similar to the for loop one you saw earlier. But because it’s the reduce() method, the syntax is more complex. Thus, you should stay away from using the reduce() method in merging arrays.

Читайте также:  Python get files tree

Conclusion

Today you learned five ways to merge arrays in JavaScript.

To recap, here are the solutions:

  1. The traditional for loop
  2. The spread operator (…)
  3. The concat() method
  4. The push() method
  5. The reduce() method

The most convenient and neat way to merge arrays in JavaScript is by using the second approach, that is, the spread operator. Also, the concat() method can do the job but its syntax is a bit misleading.

Avoid using the traditional for loop approach. It’s just excess work (unless you’re practicing the basics of JavaScript).

Also, don’t do that reduce() method approach. Even though it works, it’s very similar to the for loop approach. Yet it’s pretty unreadable and can cause some headaches.

Thanks for reading! Happy coding!

Further Reading

Источник

Array.prototype.concat()

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Try it

Syntax

concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) 

Parameters

Arrays and/or values to concatenate into a new array. If all valueN parameters are omitted, concat returns a shallow copy of the existing array on which it is called. See the description below for more details.

Return value

Description

The concat method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property Symbol.isConcatSpreadable set to a truthy value, each element of the argument will be independently added to the final array. The concat method does not recurse into nested array arguments.

The concat() method is a copying method. It does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains the same elements as the ones from the original arrays.

The concat() method preserves empty slots if any of the source arrays is sparse.

The concat() method is generic. The this value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy @@isConcatSpreadable will be spread into the resulting array.

Examples

Concatenating two arrays

The following code concatenates two arrays:

const letters = ["a", "b", "c"]; const numbers = [1, 2, 3]; const alphaNumeric = letters.concat(numbers); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3] 

Concatenating three arrays

The following code concatenates three arrays:

const num1 = [1, 2, 3]; const num2 = [4, 5, 6]; const num3 = [7, 8, 9]; const numbers = num1.concat(num2, num3); console.log(numbers); // results in [1, 2, 3, 4, 5, 6, 7, 8, 9] 

Concatenating values to an array

The following code concatenates three values to an array:

const letters = ["a", "b", "c"]; const alphaNumeric = letters.concat(1, [2, 3]); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3] 

Concatenating nested arrays

The following code concatenates nested arrays and demonstrates retention of references:

const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.log(numbers); // results in [[1], 2, [3]] // modify the first element of num1 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]] 

Concatenating array-like objects with Symbol.isConcatSpreadable

concat does not treat all array-like objects as arrays by default — only if Symbol.isConcatSpreadable is set to a truthy value (e.g. true ).

const obj1 =  0: 1, 1: 2, 2: 3, length: 3 >; const obj2 =  0: 1, 1: 2, 2: 3, length: 3, [Symbol.isConcatSpreadable]: true >; console.log([0].concat(obj1, obj2)); // [ 0, < '0': 1, '1': 2, '2': 3, length: 3 >, 1, 2, 3 ] 

Using concat() on sparse arrays

If any of the source arrays is sparse, the resulting array will also be sparse:

.log([1, , 3].concat([4, 5])); // [1, empty, 3, 4, 5] console.log([1, 2].concat([3, , 5])); // [1, 2, 3, empty, 5] 

Calling concat() on non-array objects

If the this value is not an array, it is converted to an object and then treated in the same way as the arguments for concat() . In this case the return value is always a plain new array.

.log(Array.prototype.concat.call(>, 1, 2, 3)); // [<>, 1, 2, 3] console.log(Array.prototype.concat.call(1, 2, 3)); // [ [Number: 1], 2, 3 ] const arrayLike =  [Symbol.isConcatSpreadable]: true, length: 2, 0: 1, 1: 2, 2: 99, // ignored by concat() since length is 2 >; console.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4] 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Merge Arrays in JavaScript: With and Without Duplicates

Divya Dev

Divya Dev Last updated Feb 19, 2023

If you already understand the basics of JavaScript arrays, it’s time to take your skills to the next level with more advanced topics. In this series of tutorials, you’ll explore intermediate-level topics for programming with arrays in JavaScript.

In this post, you’ll learn how to combine multiple arrays into a single array in JavaScript. This is known as merging arrays. This is a simple problem that has multiple solutions. I’ll show you the most widely used and optimal ways of merging arrays.

The way you merge arrays depends on whether you want to remove duplicate values and whether you want to modify the original array or create a new array. We’ll look at each kind in this post.

Method Modifies Array? Duplicates? Time Complexity
[. ] spread operator immutable keeps duplicates O(N)
Array.concat() immutable keeps duplicates O(N)
Array.push() modifies array keeps duplicate O(N)
for loop modifies array removes duplicates O(N 2 )
filter and concat immutable removes duplicates O(N 2 )
Set immutable removes duplicates O(N)

Merge Arrays Allowing Duplicate Values

Spread Operator

One of the newest and most concise ways to perform an array merge is with the spread operator. The spread operator [. ] syntax allows two or more arrays to be adjoined. This will create a new array, without modifying the parent arrays.

const mergedArray = [. array1, array2] 

This method does not remove duplicates. Instead, all the array elements in the merged array will be inserted in the same order as the source. Here is an example to help you understand:

Источник

Оцените статью