How to add arrays in JavaScript? [SOLVED]


JavaScript

Introduction

In JavaScript, arrays are a powerful data type that allow you to store and manipulate collections of items. The Array.prototype.concat() method is a useful tool for working with arrays, as it allows you to combine two or more arrays into a single, new array. In this article, we'll explore how to use concat() to add arrays together and some common use cases for this method.

 

Using the concat() method

Before we go into the details, let’s see the typical syntax for the concat() method

const newarray = array1.concat(array2);

To add two arrays together using the concat() method, you would first need to create two arrays that you want to combine. Let's say you have two arrays called array1 and array2, and you want to add them together to create a new array called combinedArray. Here's how you would do that using the concat() method:

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];

let combinedArray = array1.concat(array2);

console.log(combinedArray);

Output

[ 1, 2, 3, 4, 5, 6 ]

As you can see, the concat() method allows you to combine two arrays together into a single array. It does this by creating a new array and copying all of the elements from both of the original arrays into the new array. You can use the concat() method to combine any number of arrays together, not just two.

It's important to note that the concat() method does not modify the original arrays. Instead, it creates a new array that contains the elements from the original arrays.

Another example where the some of the content in the first array are present in the second array. Here, we have two Deepak in the final array.

let array1 = ["Wonderful", "Deepak"];
let array2 = ["Deepak", "Gabriel"];

array1 = array1.concat(array2);

console.log(array1);

Output

[ 'Wonderful', 'Deepak', 'Deepak', 'Gabriel' ]

We might want to remove the duplicate elements that might be present. There are two approaches we might use.

One is to create a unique method and add it to the Array prototype.

Array.prototype.unique = function () {
    var a = this.concat();
    for (var i = 0; i < a.length; ++i) {
        for (var j = i + 1; j < a.length; ++j) {
            if (a[i] === a[j]) a.splice(j--, 1);
        }
    }

    return a;
};

The above code defines a new function called unique that can be called on an array object. The function creates a new array called a which is a copy of the original array that the function was called on. It then iterates through the elements of the new array, and for each element, it checks the remaining elements to see if there are any duplicates.

If it finds a duplicate, it removes it from the array using the splice method. Finally, the function returns the modified array.

Now, we can use the unique method on the concated array.

let array1 = ["Wonderful", "Deepak"];
let array2 = ["Deepak", "Gabriel"];

array1 = array1.concat(array2).unique();
console.log(array1);

Output

[ 'Wonderful', 'Deepak', 'Gabriel' ]

However, there is a better way that makes use of the Set object and the spread operator.

let array1 = ["Wonderful", "Deepak"];
let array2 = ["Deepak", "Gabriel"];

array3 = [...new Set(array1.concat(array2))];
console.log(array3);

Output

[ 'Wonderful', 'Deepak', 'Gabriel' ]

Here, we use the spread operator (...) to spread the elements of array1 and array2 into a new array (say tempArray). This creates a new array that contains all the elements of array1 and array2 in the order that they appear.

Next, the code uses the Set object to create a new set from the elements of tempArray. A set is a collection of unique values, so creating a set from an array removes any duplicate elements.

Finally, the code uses the spread operator again to spread the elements of the set back into an array, which is then assigned to the "array3" variable.

The resulting array3 array will contain all the elements of array1 and array2, with any duplicates removed.

 

Using the push() method

If you want to add the elements from one array to another array without creating a new array, you can use the push() method instead. Here's an example of how you would use the push() method to add the elements from one array to another array:

let array1 = [1, 2, 3];
let array2 = [4, 5, 6];

array1.push(array2);

console.log(array1);

Output

[ 1, 2, 3, [ 4, 5, 6 ] ]

As you can see, using the push() method adds the entire array2 array as a single element to the end of the array1 array. This is different from the concat() method, which adds the individual elements from both arrays to a new array.

 

Summary

For you to achieve adding arrays, we can make use of the concat method, but the push method can be another approach depending on your objective. In addition, we can make use of built-in functionalities such as the Set object and the spread ooer

 

References

Array.prototype.concat() - JavaScript | MDN (mozilla.org)
Array.prototype.push() - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment