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]
.
This question is related to
javascript
arrays
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);
_x000D_
const array_one = [11, 22, 33, 44, 55];_x000D_
const start = 1;_x000D_
const end = array_one.length - 1;_x000D_
const array_2 = array_one.slice(start, end);_x000D_
console.log(array_2);
_x000D_
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) {_x000D_
if (null == obj || "object" != typeof obj) return obj;_x000D_
const copy = obj.constructor();_x000D_
for (const attr in obj) {_x000D_
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];_x000D_
}_x000D_
return copy;_x000D_
}_x000D_
_x000D_
// With the `clone()` function, you can now do the following:_x000D_
_x000D_
Array.prototype.subarray = function(start, end) {_x000D_
if (!end) {_x000D_
end = this.length;_x000D_
} _x000D_
const newArray = clone(this);_x000D_
return newArray.slice(start, end);_x000D_
};_x000D_
_x000D_
// Without a copy you will lose your original array._x000D_
_x000D_
// **Example:**_x000D_
_x000D_
const array = [1, 2, 3, 4, 5];_x000D_
console.log(array.subarray(2)); // print the subarray [3, 4, 5, subarray: function]_x000D_
_x000D_
console.log(array); // print the original array [1, 2, 3, 4, 5, subarray: function]
_x000D_
[http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]
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).
Source: Stackoverflow.com