Reputation: 29
In this code, I don't understand the use of spread operator (...) before calling the function in the if statement. In the code below, the answer is [1, 2, 3, 4] which is the correct answer.
function steamrollArray(arr) {
const flattenedArray = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flattenedArray.push(...steamrollArray(arr[i]));
} else {
flattenedArray.push(arr[i]);
}
}
return flattenedArray;
};
console.log(steamrollArray([1, [2], [3, [[4]]]]))
// answer = [1, 2, 3, 4 ]
However, if I delete the spread operator the function calling, answer will be [ 1, [ 2 ], [ 3, [ [Array] ] ] ]. I don't understand the use of spread operator in this context.
function steamrollArray(arr) {
const flattenedArray = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flattenedArray.push(steamrollArray(arr[i]));
} else {
flattenedArray.push(arr[i]);
}
}
return flattenedArray;
};
console.log(steamrollArray([1, [2], [3, [[4]]]]))
// answer = [ 1, [ 2 ], [ 3, [ [Array] ] ] ]
Upvotes: 0
Views: 438
Reputation: 121
Firstly, you should know that the push
method accept any number of argument.
ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
Secondly, the spread operator will help you flat
the array become each argument of method.
For example,
const b = [1,2,3,4];
x.push(...b) //
x.push(1,2,3,4)//
Here is your function without spread operator
function steamrollArray(arr) {
const flattenedArray = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
const result = steamrollArray(arr[i]);
for (let j = 0; j < result.length; j++) {
flattenedArray.push(result[j]);
}
} else {
flattenedArray.push(arr[i]);
}
}
return flattenedArray;
};
Upvotes: 0
Reputation: 28196
The "three dots" or the spread syntax turns an array into a list of individual values, like arguments in a function call:
(...[1,3,3]) --> (1,2,3)
( [1,2,3]) --> ([1,2,3])
In the context of the steamroller()
this is the chosen way to flatten each individual array element.
Upvotes: 2
Reputation: 1074198
Spread syntax (it's not an operator) spreads out the entries from the array into discrete arguments to push
. So for instance, if steamrollArray
returnd [1, 2, 3]
, then
flattenedArray.push(...steamrollArray(/*...*/));
would be like
flattenedArray.push(1, 2, 3);
That calls push
with three separate arguments (the elements from the array). But if you remove the spread, it's like:
flattenedArray.push([1, 2, 3]);
That calls push
with one argument: an array to push. So you end up with an array inside the array, instead of the array's elements in the array.
Compare:
const someArray = [1, 2, 3];
const flattenedArray = [];
flattenedArray.push(...someArray);
console.log(flattenedArray);
with
const someArray = [1, 2, 3];
const flattenedArray = [];
flattenedArray.push(someArray); // no spread
console.log(flattenedArray);
Upvotes: 3