# How to get subarray from array?

## How to get subarray from array?

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

### Solution 1:

Take a look at `Array.slice(begin, end)`

``````var ar  = [1, 2, 3, 4, 5];

var ar2 = ar.slice(1, 3 + 1); // slice from 1..3 - add 1 as the end index is not included

console.log(ar2);

>>[ 2, 3, 4 ]
``````

### Solution 2:

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 other language (.i.e: Groovy )

### Solution 3:

``````var array_one = [11, 22, 33, 44,55];
var start = 1;
var end = array_one.length-1
var array_2 = array_one.slice(start, end);
console.log(array_2)
``````

### Solution 4:

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;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
[http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]
``````

With the `clone()` function, you can now do the following:

``````Array.prototype.subarray=function(start, end) {
if(!end){
end = this.length;
}
var newArray = clone(this);
return newArray.slice(start, end);
};
``````

Without a copy you will lose your original array.

Example:

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