Add Arrays in JavaScript with concat() and Set

Tech reviewed: Deepak Prasad
Add Arrays in JavaScript with concat() and Set

Adding arrays in JavaScript usually means combining two or more arrays into one result. The most common tools for that job are concat(), spread syntax, and Set when you also want to remove duplicates.

This is a practical pattern for list merging, report building, and data cleanup. If you are going to dedupe values afterward, deduplicating a JavaScript array is the next related topic.

Tested On: The examples were tested with Node.js v20.18.1 on a Linux system. The same array behavior works in modern browsers and JavaScript runtimes.


Method 1: Add arrays with concat()

concat() joins arrays and returns a new array without changing the originals.

javascript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combined = array1.concat(array2);

console.log("add-arrays:", combined.join(","));

Tested output:

text
add-arrays: 1,2,3,4,5,6

Use this when you want to merge arrays and keep the source arrays untouched.


Method 2: Add arrays with spread syntax

Spread syntax gives you a short way to build a new array from existing arrays.

javascript
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combined = [...array1, ...array2];

console.log("add-arrays-spread:", combined.join(","));

Tested output:

text
add-arrays-spread: 1,2,3,4,5,6

This is the cleanest approach when you want a direct literal-style merge.


Method 3: Add arrays and remove duplicates

Set removes duplicate primitive values after the arrays are combined.

javascript
const array1 = [1, 2, 3];
const array2 = [3, 4];
const unique = [...new Set(array1.concat(array2))];

console.log("add-arrays-set:", unique.join(","));

Tested output:

text
add-arrays-set: 1,2,3,4

This is the right pattern when you want a merged array without repeated primitive values.


Summary

To add arrays in JavaScript, use concat() when you want a familiar merge, use spread syntax when you want compact code, and use Set when you also need to remove duplicates. Together these patterns cover most merge-and-dedupe tasks without extra libraries.


Official documentation

Olorunfemi Akinlua

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 …

  • JavaScript
  • Web Design