Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat 2 sliced array?

I have:

var a = [1,2,3,4,5,6,7,8,9]

and I'm trying to do:

var b = [];
b.concat(a.slice(0,3), a.slice(-3))

And as a result I have:

b == []

How I can get 3 first and 3 last elements from an array at b?

like image 366
Viacheslav Kondratiuk Avatar asked Feb 24 '26 05:02

Viacheslav Kondratiuk


2 Answers

concat doesn't work inline on the array. The result of concat() has to be catched.

The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.

You're not updating the value of b array.

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var b = [].concat(a.slice(0, 3), a.slice(-3));

document.write(b);
console.log(b);

You can also concat the sliced arrays.

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var b = a.slice(0, 3).concat(a.slice(-3));

document.write(b);
console.log(b);
like image 141
Tushar Avatar answered Feb 25 '26 17:02

Tushar


Array.prototype.concat has no side effects, meaning it does not modify the original array (i.e. b)

I see two ways of achieving what you want:

Assigning the result of concat to b (it will break the reference to the original array, since it is a fresh new one)

b = b.concat(a.slice(0,3), a.slice(-3));

Or using Array.prototype.push and apply to modify b in place

Array.prototype.push.apply(b, a.slice(0,3).concat(a.slice(-3)));

This one is a bit tricky. Why would you use apply?

Because doing b.push(a.slice(0, 3), a.slice(0 - 3)) would have resulted in a different structure: [[...], [...]]

For more information about apply see the documentation for Function.prototype.apply

like image 44
axelduch Avatar answered Feb 25 '26 19:02

axelduch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!