I have var ar = [1, 2, 3, 4, 5]
and want some function getSubarray(array, fromIndex, toIndex)
, that result of call getSubarray(ar, 1, 3)
is new array [2, 3, 4]
.

- 341,306
- 83
- 791
- 678

- 25,747
- 28
- 93
- 153
-
10Have you tried [slice](http://www.w3schools.com/jsref/jsref_slice_array.asp)? – Tom Knapen Sep 24 '11 at 10:48
5 Answers
Take a look at Array.slice(begin, end)
const ar = [1, 2, 3, 4, 5];
// slice from 1..3 - add 1 as the end index is not included
const ar2 = ar.slice(1, 3 + 1);
console.log(ar2);

- 21,961
- 19
- 54
- 57

- 171,639
- 30
- 264
- 288
-
68It's probably worth explicitly mentioning here that the original `ar` is unmodified. `console.log(ar);` `// -> [1, 2, 3, 4, 5]` – daemone Dec 18 '18 at 18:35
-
2Also, don't make the mistake of confusing the `slice()` method with `splice()`: `splice()` changes the original array while `slice()` doesn't. – Vladimir Fokow Nov 07 '21 at 15:52
-
I'm sorry, but what if I try to slice using parameters, that'd raise some sort of "index out of bounds" error? In the example imagine I'd go with `ar.slice(4, 4);`? I guess I should try out :x.. – Igor Nov 30 '21 at 23:03
-
2@Igor No, slice does not raise an exception. If the `end` is greater than the length of the sequence, slice extracts through to the end of the sequence (`arr.length`). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice – JM217 Dec 14 '21 at 16:54
-
I want to add another note that `slice` does not raise exceptions for any type of input (string, undefined, object whatever). If `start` is out of range (negative or greater than the length), it just returns an empty array. – JM217 Jul 17 '22 at 15:12
For a simple use of slice
, use my extension to Array Class:
Array.prototype.subarray = function(start, end) {
if (!end) { end = -1; }
return this.slice(start, this.length + 1 - (end * -1));
};
Then:
var bigArr = ["a", "b", "c", "fd", "ze"];
Test1:
bigArr.subarray(1, -1);
< ["b", "c", "fd", "ze"]
Test2:
bigArr.subarray(2, -2);
< ["c", "fd"]
Test3:
bigArr.subarray(2);
< ["c", "fd","ze"]
Might be easier for developers coming from another language (i.e. Groovy).

- 64
- 4

- 87,526
- 38
- 249
- 254
-
24[Don't modify objects you don't own](https://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/) – Kartik Chugh Jul 18 '18 at 16:44
-
2What K_7 said; most especially, monkey-patching the Builtins (Object, Array, Promise, etc) is *very* naughty. See the famous example of [MooTools forcing a rename](https://github.com/tc39/Array.prototype.includes/commit/4b6b9534582cb7991daea3980c26a34af0e76c6c) of the proposed native `Array.prototype.contains` to `Array.prototype.includes`. – daemone Jan 08 '19 at 10:26
-
1Not to mention, your `subarray` method delivers unexpected results. `bigArr.slice(1,-1)` returns `['b','c','fd']`, which you would expect (the -1 knocks one element off the end of the new array). But `bigArr.subarray(1,-1)` returns the same as `bigArr.subarray(1)`, which is to say *everything* from position 1 to the end of `bigArr`. You're also forcing users to always give negative numbers as the `end` parameter. Any `end >= -1` gives the same result as when `end === undefined`. On the other hand, `bigArr.slice(1,3)` returns `['b','c']`, which again is expected. – daemone Jan 08 '19 at 10:38
const array_one = [11, 22, 33, 44, 55];
const start = 1;
const end = array_one.length - 1;
const array_2 = array_one.slice(start, end);
console.log(array_2);

- 405
- 7
- 17

- 4,133
- 3
- 33
- 55
-
it does not compile here the correction : var array_one = [11, 22, 33, 44,55]; var ar2 = array_one.slice(0, array_one.length-1); console.log(ar2) – bormat Mar 19 '18 at 17:33
I have var ar = [1, 2, 3, 4, 5] and want some function getSubarray(array, fromIndex, toIndex), that result of call getSubarray(ar, 1, 3) is new array [2, 3, 4].
Exact Solution
function getSubarray(array, fromIndex, toIndex) {
return array.slice(fromIndex, toIndex+1);
}
Let's Test the Solution
let ar = [1, 2, 3, 4, 5]
getSubarray(ar, 1, 3)
// result: [2,3,4]
Array.prototype.slice()
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
Basically, slice lets you select a subarray from an array.
For example, let's take this array:
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
Doing this:
console.log(animals.slice(2, 4));
Will give us this output:
// result: ["camel", "duck"]
Syntax:
slice() // creates a shallow copy of the array
slice(start) // shows only starting point and returns all values after start index
slice(start, end) // slices from start index to end index

- 3,029
- 26
- 18
The question is actually asking for a New array, so I believe a better solution would be to combine Abdennour TOUMI's answer with a clone function:
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
const copy = obj.constructor();
for (const attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
// With the `clone()` function, you can now do the following:
Array.prototype.subarray = function(start, end) {
if (!end) {
end = this.length;
}
const newArray = clone(this);
return newArray.slice(start, end);
};
// Without a copy you will lose your original array.
// **Example:**
const array = [1, 2, 3, 4, 5];
console.log(array.subarray(2)); // print the subarray [3, 4, 5, subarray: function]
console.log(array); // print the original array [1, 2, 3, 4, 5, subarray: function]
[http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]

- 405
- 7
- 17

- 353
- 3
- 8
-
10
-
10`Array.prototype.slice` returns a copy already. `Array.prototype.splice` modifies the original array. – Guido Bouman Feb 07 '16 at 20:51
-
2The slice() method returns a shallow copy of a portion of an array into a new array object. See [Mozilla Developer Network](https://developer.mozilla.org/en-S/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). Downvoted. – TheCrazyProgrammer Mar 03 '17 at 18:34
-
As others have said, `slice` already returns a shallow copy, making this `subarray` implementation unnecessary. But it's also worth mentioning you've monkey-patched a builtin object, which is a big no-no. See the comments on [Abdennour TOUMI's answer](https://stackoverflow.com/a/18359274/2211532). – daemone Jan 08 '19 at 11:00