Merge arrays in JavaScript: with and without duplicates


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

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

How 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 will look at each type in this post.

Merge arrays allowing duplicate values

Diffusion operator

One of the newest and most concise ways to do an array merge is with the spread operator. The diffusion operator [...] the syntax allows the union of two or more arrays. This will create a new array, without affecting the main arrays.

1
const mergedArray = [...array1, array2]

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

1
const array1 = [1,2,3]
2
const array2 = [1,2,4]
3

4
const merged = [...array1, array2]
5
console.log(merged) // [1, 2, 3, 1, 2, 4]

Time Complexity of the Spread operator

The Spread operator makes use of [Symbol.iterator], which is a property of the object. In the case of joining two arrays, the spread operator iterates over each element of the array using the method .next() function. This results in a time complexity of O(N).

The overall time complexity of the spread operator is O(N).

Array Concat

If you are looking for a functional method to join arrays, Array.concat() it will be useful. Also, if you’re not sure about the input type, use Array.concat().

1
const mergedArray = array1.concat(array2)

Also, you can use this syntax:

1
const mergedArray = [].concat(array1, array2)

THE concat function is also an immutable way of joining to arrays. It doesn’t modify the main arrays, but creates a new merged array. The elements of the array will be inserted in the same order as the source.

1
const array1 = [1,2,3]
2
const array2 = [1,2,4]
3

4
const merged = [].concat(array1, array2)
5
or
6
const merged = array1.concat(array2)
7
console.log(merged) // [1, 2, 3, 1, 2, 4]

THE concat The function allows you to join two or more arrays together.

1
const mergedArray = array1.concat(array2, array3, array4 .... arrayN);

Time Complexity

THE concat function can perform better than the spread operator. This is why concat uses array-specific optimization methods. On the other hand, the spread operator is based on common iteration protocols. I have tested some large arrays on different browsers to compare the spread and operator concat:








Navigator Diffusion operator Concat
Chrome 626.5 ms 230.1 ms
firefox 900.40 ms 820.20 ms
Edge 1740.7 ms 700.3 ms
Safari 165.3 ms 144.34 ms

The overall time complexity is del concat function is O(N).

Matrix boost

If the array merge method should not create a new array, array.push it will be useful. This method allows you to merge an element, in an array, into an existing one. The newly added element will be inserted at the end of the array. This does array.push A changing way to merge.

1
const array1 = [1,2,3]
2
array1.push(4)
3
array2.push(2)
4
console.log(array1) // [1, 2, 3, 4, 2]

You can insert an array into an existing array using the spread operator.

1
const array1 = [1,2,3]
2
const array2 = [1,2,4]
3
array1.push(...array2)
4

5
console.log(array1) // [1, 2, 3, 1, 2, 4]

When you want to join two or more arrays, using array.push() you can use the following syntax:

1
const array1 = [1,2,3];
2
const array2 = [4,5,6];
3
const array3 = [7,8,9];
4

5
array1.push(...[...array2, ...array3]); // [1,2,3,4,5,6,7,8,9]

Time complexity

Array push operation costs O(1) for a single element. If you want to join N elements, it will cost O(N). When merging the array, a copy cost of O(N) will be charged when an array slot is allocated and a new element is inserted.

The overall time complexity of Array.push is O(N).

Merge arrays and remove duplicate values

The traditional For Loop

The traditional method for joining two arrays involves two or more for loops based on the number of arrays.

Algorithm

  1. iterate through each element of the new array
  2. usage indexOf() to judge if that element is already present in the old array
  3. if it’s not there, add it to the old array
1
function merge(array1, array2) {
2
    for (let i=0; i<array2.length; i++) 
3
        if (array1.indexOf(array2[i])==-1)
4
            array1.push(array2[i]);
5
            
6
    return array1;
7
}

Time complexity

To merge two arrays of the same size using this algorithm, the indexOf The method must be called for each of the N elements of the new array. And every call to indexOf takes O(N) time to search the old array. So the overall time complexity is O(N2).

The overall time complexity of a for loop union with duplicates removed is O(N2).

Filter and Concat With ES5

This solution replaces for loops with built-in array functions concat AND filter.

concat() can be used to join multiple arrays together. But it doesn’t remove duplicates.

filter() is used to remove duplicates from merged array. Just like the traditional for loop, the filter uses the indexOf() method for judging the occurrence of an element in the merged array.

Algorithm

  1. concat() arrays together and store them in another array
  2. Use the filter() to iterate through the merged array and remove any elements that occur multiple times
1
function merge(array1, array2) {
2
    let arrayMerge = array1.concat(array2)
3
    return arrayMerge.filter( (item, index) =>
4
        arrayMerge.indexOf(item) == index
5
    )
6
}

Time complexity

To join two arrays of the same size with this algorithm, concat takes O(N) time. Then the filter calls indexOf on each element of the resulting array, again with O(N2) time.

The overall time complexity of the filter AND concat the solution is O(N2).

Merging arrays with a set

The ES6 offers a single line solution for merging arrays without duplicates. Use the spread operator and a Set.

Set is a data structure built into JavaScript ES6 and later that doesn’t support duplicates. This is where concat() AND Set divert-Set check for duplicates and remove them. Hence, a large part of our work is done by the data structure.

Code for merging arrays with a set

  1. collect the unique values ​​for the two arrays in a Set
  2. use the spread operator to convert the file Set go back to an array
1
function merge(array1, array2) {
2
    return [... new Set[...array1, ...array2])];
3
}

Time complexity

To join two arrays using Setthe time complexity is O(N).

Conclusion

So far, we’ve seen more than a single way to join two arrays in JavaScript. If you are ready to merge duplicates, the most optimal solutions include concat and the diffusion operator.

We also saw how to remove duplicates from merged arrays. The solution offered by ES6 is the simplest and least expensive. With a time complexity of O(n), this is the ideal choice for any merging of two or more arrays when removing duplicates.



Source link

By LocalBizWebsiteDesign

Leave a Reply

Your email address will not be published. Required fields are marked *