ES6

How to merge arrays using the spread syntax in ES6?

This blog describes how to merge arrays using the spread syntax in ES6.

In ES6, you can merge arrays using the spread syntax (...). The spread syntax allows you to expand elements of an iterable (like an array) into places where multiple elements are expected. For example.

// Arrays to be merged
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

// Merging arrays using the spread syntax
const mergedArray = [...array1, ...array2];

console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

Output

Merge arrays using the spread syntax in ES6
Merge arrays using the spread syntax in ES6

n this example, [...array1, ...array2] is using the spread syntax to merge array1 and array2 into a new array called mergedArray. The spread syntax ...array1 expands the elements of array1, and ...array2 expands the elements of array2, resulting in a single array containing all the elements from both arrays.

You can merge multiple arrays in the same way.

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

const mergedArray = [...array1, ...array2, ...array3];

console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]

This method creates a new array and leaves the original arrays unchanged. If you want to merge arrays without creating a new one, you would need to use methods like push() or concat().


Further Reading

JUnit Tutorial

Spring Framework Practice Problems and Their Solutions

30 MCQs on JUnit

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

100+ MCQs On Java Architecture

Java Practice Exercise

programmingempire

Princites

You may also like...

Leave a Reply

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