The code below,
console.log([].concat.apply([2],[[99],5,6,[2,3]]));
outputs
[ 2, 99, 5, 6, 2, 3 ]
And the code below,
console.log([2].concat([99]).concat([5,6,[2,3]]));
outputs
[ 2, 99, 5, 6, [ 2, 3 ] ]
My assumption was that the output of
console.log([].concat.apply([2],[[99],5,6,[2,3]]));
Should be
[2,[99],5,6,[2,3]]
But its not, why ?
concat() The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
To solve the error, console. log the value you're calling the concat method on and make sure it's a valid array. Copied! const arr1 = [{name: 'Tom'}]; const arr2 = [{name: 'James'}]; const arr3 = arr1.
. concat takes the multiple arguments, and merges all the arrays (and non-array arguments) into a single array. Basically, the array arguments get unpacked 1 level. To get that output, you would have to wrap each of the array elements in an additional array.
The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
That's because:
console.log( [].concat.apply([2],[[99],5,6,[2,3]]) );
is equivalent to:
console.log( [2].concat([99], 5, 6, [2,3]) );
.concat
takes the multiple arguments, and merges all the arrays (and non-array arguments) into a single array. Basically, the array arguments get unpacked 1 level.
To get that output, you would have to wrap each of the array elements in an additional array.
console.log( [].concat.apply([2],[[[99]],5,6,[[2,3]]]) );
Perhaps you would prefer to use a .push
based approach.
var a = [2];
a.push.apply(a, [[99],5,6,[2,3]]);
console.log(a);
Your assuming about in a way without seeing the document. See, the actual syntax for concat is,
Array.prototype.concat ( [ item1 [ , item2 [ , … ] ] ] )
So your code is barely equals to,
[].concat.apply([itm1], [itm2,itm3,itm4]...)
From your code's point of view, your code is similar to,
[2].concat([99],5,6,[2,3]);
let's dismantle your code,
console.log([].concat.apply([2],[[99],5,6,[2,3]]));
// 1. apply will call the function by applying the parameter supplied as an array.
// 2. so the first parameter for apply would be this for that function
// 3. and the second parameter for it would be the arguments in an array form.
// 4. Hence internally apply will call the function concat as,
// [2].concat([99],5,6,[2,3]); //[2] will be 'this'
But for your requirement, you don't need to go with apply
, you can use call
.
console.log([].concat.call([2],[[99],5,6,[2,3]]));
//[2,[99],5,6,[2,3]]
Note, apply
effectively is a spread operator for the second argument. so
console.log([].concat.apply([2],[[99],5,6,[2,3]]));
console.log([2].concat(...[[99],5,6,[2,3]])); // * using es6 spread operator `...`
console.log([2].concat([99],5,6,[2,3]));
console.log([2].concat([[99],5,6,[2,3]]));
The difference being the spread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With