viakondratiuk viakondratiuk - 7 months ago 10
Javascript Question

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
?

Answer

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);