Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

JavaScript - how to get subarray from array?

0 contributions
5 points

In JavaScript it is possible to split array in following way.

1. Array split method example

This method takes start-index and limit-index (excluded index) as arguments.

// ONLINE-RUNNER:browser;

var array = [
    1, 2, 3, 'text 1', 'text 2', 'text 3', true, false

//  0  1  2      3         4         5       6     7    <- positive indexes
// -8 -7 -6     -5        -4        -3      -2    -1    <- negative indexes
];

var subArray1 = array.slice(0, 4);    // [ 1, 2, 3, 'text 1' ]
var subArray2 = array.slice(2, 4);    // [ 3, 'text 1' ]
var subArray3 = array.slice(4);       // [ 'text 2', 'text 3', true, false ]
var subArray4 = array.slice(-2);      // [ true, false ]
var subArray5 = array.slice(2, -4);   // [ 3, 'text 1' ]
var subArray6 = array.slice(-5, -2);  // [ 'text 1', 'text 2', 'text 3' ]

console.log(subArray1);
console.log(subArray2);
console.log(subArray3);
console.log(subArray4);
console.log(subArray5);
console.log(subArray6);

Output (with NodeJS):

[ 1, 2, 3, 'text 1' ]
[ 3, 'text 1' ]
[ 'text 2', 'text 3', true, false ]
[ true, false ]
[ 3, 'text 1' ]
[ 'text 1', 'text 2', 'text 3' ]

Merged questions

  1. JavaScript - how to split array?
  2. How to split array in JavaScript?

  3. JavaScript - how to get sub-array?

References

  1. String.prototype.split method - MDN Docs

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more