Whether you prefer concise methods like the spread operator (
...) or need more control using functions like
This is a feature of ES6 that allows you to expand the elements of an iterable (such as an array) into individual arguments. It also preserves the order of the arrays and works with any number of arrays.
The spread operator itself does not remove duplicate elements from an array. It simply spreads the elements of one array into another, retaining all the elements, including duplicates.
const array1 = [1, 2, 3]; const array2 = [3, 4, 5]; const array3 = [...array1, ...array2]; console.log(array3); // [ 1, 2, 3, 3, 4, 5 ]
Set or write a custom function.
const array = [1, 2, 2, 3, 4, 4, 5]; const uniqueArray = [...new Set(array)]; console.log(uniqueArray); // [1, 2, 3, 4, 5]
Keep in mind that the spread operator performs shallow copying, which means it creates new references for the top-level elements in arrays or objects. Nested objects and arrays will still be shared references, so modifying them in the new array or object will affect the original as well. If you need to perform a deep copy, you may need to use other techniques or libraries like Lodash.
const array1 = [1, 2, 3]; const array2 = [3, 4, 5]; const mergedArray = array1.concat(array2); console.log(mergedArray); // [ 1, 2, 3, 3, 4, 5 ] console.log(array1); // [ 1, 2, 3 ]
You can use the
push() method in combination with the spread operator to add elements from one array to another.
const array1 = [1, 2, 3]; const arrar2 = [3, 4, 5]; array1.push(...arrar2); console.log(array1); // [1, 2, 3, 3, 4, 5]