JavaScript take part of an array
JavascriptJavascript Problem Overview
How can I create a new array that contains all elements numbered nth to (n+k)th from an old array?
Javascript Solutions
Solution 1 - Javascript
You want the slice method.
var newArray = oldArray.slice(n, n+k);
Solution 2 - Javascript
i think the slice method will do what you want.
arrayObject.slice(start,end)
Solution 3 - Javascript
Slice creates shallow copy, so it doesn't create an exact copy. For example, consider the following:
var foo = [[1], [2], [3]];
var bar = foo.slice(1, 3);
console.log(bar); // = [[2], [3]]
bar[0][0] = 4;
console.log(foo); // [[1], [4], [3]]
console.log(bar); // [[4], [3]]
Solution 4 - Javascript
Prototype Solution:
Array.prototype.take = function (count) {
return this.slice(0, count);
}
Solution 5 - Javascript
> lets say we have an array of six objects, and we want to get first three > objects.
Solution :
var arr = [{num:1}, {num:2}, {num:3}, {num:4}, {num:5}, {num:6}];
arr.slice(0, 3); //will return first three elements