Learn how to merge two or more arrays using JavaScript efficiently.
Suppose you have two arrays:
const first = ['one', 'two'];
const second = ['three', 'four'];
and you want to combine them into a single array.
How do you achieve this?
The recommended modern approach is to use the destructuring operator to create a new array:
const result = [...first, ...second];
This method is highly recommended. It is essential to note that the destructuring operator was introduced in ES6, which means older browsers (particularly Internet Explorer) may not support it.
For compatibility with older browsers, you can use the concat()
method, which can be called on any array:
const result = first.concat(second);
Both approaches generate a new array without altering the original ones.
Tags: JavaScript, arrays, concatenation, merging