JavaScript take part of an array

Javascript

Javascript 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKalElView Question on Stackoverflow
Solution 1 - JavascriptBobView Answer on Stackoverflow
Solution 2 - JavascriptEricView Answer on Stackoverflow
Solution 3 - JavascriptVictor G.View Answer on Stackoverflow
Solution 4 - JavascriptError404View Answer on Stackoverflow
Solution 5 - JavascriptMalik KhalilView Answer on Stackoverflow