84

How can I create a new array that contains all elements numbered nth to (n+k)th from an old array?

5 Answers 5

127

You want the slice method.

var newArray = oldArray.slice(n, n+k);
Sign up to request clarification or add additional context in comments.

1 Comment

While W3Schools doesn't appear to have any errors on that page (which is unusual), I think the MDC documentation is better: developer.mozilla.org/en/Core_JavaScript_1.5_Reference/…
18

i think the slice method will do what you want.

arrayObject.slice(start,end)

Comments

5

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]]

Comments

2

Prototype Solution:

Array.prototype.take = function (count) {
    return this.slice(0, count);
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.