[JavaScript]Array Concatenation – Spread Syntax vs. concat

目次

Overview

When you need to merge multiple data lists into a single collection, JavaScript offers two primary methods: the traditional concat method and the modern “Spread Syntax (…)” introduced in ES2015 (ES6). Today, spread syntax has become the standard due to its superior readability and flexibility. This article compares these two approaches and demonstrates how to integrate separate department lists into a unified master directory for a project.


Specifications (Input/Output)

Syntax Comparison

SyntaxMeaningFeatures
arr1.concat(arr2)Generates a new array by appending the second array to the first.The traditional approach. Supports method chaining.
[...arr1, ...arr2]Generates a new array by “spreading” and redefining elements.Highly recommended. Allows inserting individual values between arrays.
  • Input: Multiple arrays containing employee or data objects.
  • Output: A single, newly merged array. The original source arrays remain unchanged.

Basic Usage

1. concat Method

This method is called on an existing array and takes other arrays as arguments to join them.

const groupA = ['User1', 'User2'];
const groupB = ['User3'];

const merged = groupA.concat(groupB);
console.log(merged); // ["User1", "User2", "User3"]

2. Spread Syntax

This syntax “unpacks” the contents of an array into a new array literal. It is the modern standard for joining data.

const groupA = ['User1', 'User2'];
const groupB = ['User3'];

// Spread A and B into a new array
const merged = [...groupA, ...groupB];
console.log(merged); // ["User1", "User2", "User3"]

// It is also the easiest way to clone an array
const clone = [...groupA];

Full Code

This demonstration merges an Engineering team and a Sales team into a single project participant list. We use the spread syntax to combine a single “Leader” object with two distinct arrays.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Team Merger Demo</title>
    <style>
        .container {
            font-family: sans-serif;
            max-width: 400px;
            border: 1px solid #ccc;
            padding: 20px;
            border-radius: 8px;
            background-color: #f9f9f9;
        }
        h3 { margin-top: 0; color: #333; }
        .list-group {
            background: white;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
            list-style-type: none;
            border-radius: 4px;
        }
        .list-item {
            padding: 5px 0;
            border-bottom: 1px dashed #eee;
        }
        .list-item:last-child { border-bottom: none; }
        .badge {
            display: inline-block;
            padding: 2px 6px;
            font-size: 0.8em;
            border-radius: 4px;
            margin-right: 8px;
            color: white;
        }
        .bg-eng { background-color: #2196F3; }
        .bg-sales { background-color: #FF9800; }
        .bg-leader { background-color: #4CAF50; }
    </style>
</head>
<body>

<div class="container">
    <h3>Project Participant List</h3>
    <ul id="merged-list" class="list-group">
        </ul>
</div>

<script src="merge_teams.js"></script>
</body>
</html>

JavaScript

/**
 * Team Integration Script
 * Demonstrating array concatenation using Spread Syntax
 */

// 1. Array definitions for different departments
const engineeringTeam = [
    { name: 'Alice', role: 'Dev', dept: 'Eng' },
    { name: 'Bob', role: 'QA', dept: 'Eng' }
];

const salesTeam = [
    { name: 'Charlie', role: 'Sales', dept: 'Sales' },
    { name: 'Dave', role: 'Manager', dept: 'Sales' }
];

// A single object representing the project leader
const projectLeader = { name: 'Eve', role: 'Leader', dept: 'All' };

const listContainer = document.getElementById('merged-list');

/**
 * Merges team data and renders it to the screen
 */
const renderProjectDirectory = () => {
    // 2. Joining the data
    // Spread syntax allows us to mix single objects and arrays seamlessly
    const allMembers = [
        projectLeader,      // Add a single object at the start
        ...engineeringTeam, // Expand the engineering array
        ...salesTeam        // Expand the sales array
    ];

    // Clear existing content and render new items
    listContainer.innerHTML = '';
    
    allMembers.forEach(member => {
        let badgeClass = 'bg-eng';
        if (member.dept === 'Sales') badgeClass = 'bg-sales';
        if (member.role === 'Leader') badgeClass = 'bg-leader';

        const li = document.createElement('li');
        li.className = 'list-item';
        li.innerHTML = `
            <span class="badge ${badgeClass}">${member.role}</span>
            <span>${member.name}</span>
        `;
        listContainer.appendChild(li);
    });
};

// Execute the rendering process
renderProjectDirectory();

Customization Points

One of the most powerful aspects of the spread syntax is the ability to insert elements in the middle of the joining process. Unlike the concat method, which only appends to the end, spread syntax allows you to write [...arrA, 'New Item', ...arrB]. Additionally, you can join any number of arrays sequentially in a single line, such as [...arr1, ...arr2, ...arr3], without nesting method calls.


Important Notes

Shallow Copy Warning

Both concat and the spread syntax perform a shallow copy. While they create a new array, any objects contained within them are copied by reference. This means if you modify an object property (e.g., member.name) in the merged array, the original source array will also reflect that change.

Performance Constraints

When merging extremely large datasets (tens of thousands of items), the spread syntax can occasionally hit stack size limits because it treats the expanded items as function arguments internally. In such rare edge cases, the concat method is generally safer and more stable for memory management.


Advanced Usage

Conditional Array Merging

By combining the spread syntax with a ternary operator, you can selectively include or exclude entire arrays based on specific conditions, such as environment flags.

const coreAssets = ['main.js', 'base.css'];
const debugTools = ['logger.js', 'dev-helper.json'];
const isProduction = true;

// Only include debug tools if not in production
const finalBundle = [
    ...coreAssets,
    ...(isProduction ? [] : debugTools)
];

console.log(finalBundle); // ["main.js", "base.css"]

Conclusion

For most modern JavaScript development tasks, the spread syntax should be your primary choice for joining arrays. It provides a clean, declarative way to merge data while offering unique flexibility, such as inserting individual elements or handling conditional logic within the array literal itself. The traditional concat method remains useful when maintaining legacy codebases or when dealing with massive datasets where function argument limits might be a concern. By consistently using the spread syntax, you ensure your code remains scannable and easy for other developers to understand at a glance.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次