ES6 Array Methods
Spread Operator
The JavaScript spread operator (…) allows us to rapidly copy all or part of an existing array or object to another array or object.
Example
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];
The spread operator is often used in combination with destructuring.
Example
Assign the first and second items from numbers to variables and put the rest in an array:
const numbers = [1, 2, 3, 4, 5, 6];
const [one, two, ...rest] = numbers;
We can also use the spread operator on objects:
Example
Combine these two objects:
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
}
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'
}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}
The values that did not match were combined, but the property that did match, color, was overridden by the final object passed, updateMyVehicle. The resultant color is now yellow.