Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 739
Sergey Metlov Avatar asked Sep 24 '11 10:09

Sergey Metlov


People also ask

How do you create a subarray from an array?

Use the copyOfRange() to Create a Subarray From an Array in Java. Java provides us with a way to copy the elements of the array into another array. We can use the copyOfRange() method, which takes the primary array, a starting index, and an ending index as the parameters and copies that subarray to the destined array.

How do you find the total subarray of an array?

The total number of subarrays in an array of size N is N * (N + 1) / 2. The count of subarrays with an odd product is equal to the total number of continuous odd elements present in the array. Therefore, count of subarrays with even product = (Total number of subarrays – Subarrays with the odd product).

What is a subarray of an array?

A subarray is commonly defined as a part or section of an array. An array is a set of variables that a programmer defines collectively. Instead of creating separate variables, the programmer can declare a single array with multiple values labeled.


1 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);
like image 149
Alex K. Avatar answered Sep 22 '22 15:09

Alex K.