Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split an array into two arrays in javascript?

I have an array var plans=[a, b, c, d ]; with prices based monthly any yearly.

Consider- a and b are monthly and c and d are yearly.

So, I want to split the array based on the monthly and yearly values and store the values in to separate arrays

var monthly_plans=[]; and  var yearly_plans=[]

So, how do I do this?

I have used the js split() function before but on a very basic level.


2 Answers

split() is a method of the String object, not of the Array object.

From what I understand from your question, you need the Array.prototype.slice() method instead:

The slice() method returns a shallow copy of a portion of an array into a new array object.

Syntax

arr.slice([begin[, end]])

In conclusion, you may want to do something like this:

var monthly_plans = plans.slice(0, 2);
var yearly_plans = plans.slice(2);
like image 182
Zoli Szabó Avatar answered Sep 07 '25 17:09

Zoli Szabó


You can use the slice(start, end) function on arrays, e.g.

monthly_plans = plans.slice(0,2);
yearly_plans = plans.slice(2,4);

More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

like image 41
Otto Avatar answered Sep 07 '25 16:09

Otto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!