Sergey Metlov
Sergey Metlov

Reputation: 26291

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

Upvotes: 399

Views: 574359

Answers (5)

Alex K.
Alex K.

Reputation: 175768

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); // -> [2, 3, 4]
// the original ar is unmodified.
console.log(ar); // -> [1, 2, 3, 4, 5]

Upvotes: 598

Stas Sorokin
Stas Sorokin

Reputation: 3723

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

See shallow copy reference

Upvotes: 8

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93173

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

Upvotes: 17

user73362
user73362

Reputation: 363

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]

Upvotes: 1

hannad rehman
hannad rehman

Reputation: 4331

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);

Upvotes: 7

Related Questions