Spread operator and array merging in JavaScript
Let's say we have two arrays:
let arr1 = ['a', 'b', 'c'];
let arr2 = [1, 2, 3];
Let's make sure that the elements of the array
arr1 are inserted between the first
and second elements of the array arr2.
In other words, we want to write code that
will make the following array from the
current array arr2:
[1, 'a', 'b', 'c', 2, 3]
The problem, in general, can be solved
through the splice method. However,
this task is much easier to solve
through spread:
let arr1 = ['a', 'b', 'c'];
let arr2 = [1, ...arr1, 2, 3];
console.log(arr2); // shows [1, 'a', 'b', 'c', 2, 3]
Without running the code, determine what will be output to the console:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr = ['a', ...arr1, 'b', 'c', ...arr2];
console.log(arr);
Without running the code, determine what will be output to the console:
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr = ['a', ...arr1, ...arr1, 'b', 'c'];
console.log(arr);
Without running the code, determine what will be output to the console:
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5, 6];
let arr = ['a', 'b', 'c', ...arr2];
console.log(arr);
Without running the code, determine what will be output to the console:
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5, 6];
let arr3 = [...arr2, 7, 8, 9];
let arr = [0, ...arr3];
console.log(arr);
Without running the code, determine what will be output to the console:
let arr1 = [1, 2, 3];
let arr2 = [...arr1];
console.log(arr2);