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
?
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
?
3 Answers
Reset to default 7concat
doesn't work inline on the array. The result of concat()
has to be catched.
The
concat()
method returns a new array prised 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);
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
I understand you. Some of the older JS array functions are very silly. They don't return what you want just like push()
which returns the length of the resulting array instead of returning a reference to the resulting array. There have been times i want to delete an item and pass the resulting array as an argument to a function at the same time. That's where your question walks in. I have an array
var arr = [1,2,3,4,5,6,7,8,9];
and i want to delete item 5 and pass the array as an argument. Assume i
is 4.
myRecursiveFunction(arr.splice(i,1));
won't cut. The silly thing will pass the deleted element in an array to the function instead of a reference to the array called upon. But i don't want to do several instructions. I just want to pass it to a function as a single instruction's return value. So i have to e up with inventions like.
myRecursiveFunction(arr.slice(0,i).concat(arr.slice(i+1)));
Anybody with a better idea please let me know.