Rohil Patel
Rohil Patel

Reputation: 265

How to create an small array from large array in javascript

I am using jquery.bracket lib. I want to seperate an large array in pairs like ["'Team 1', 'Team 2'"],["'Team 3', 'Team 4'"] from

var all= ["'Team 1', 'Team 2'","'Team 3', 'Team 4'"]

I have tried this method:

var longArray = all;   
var shortArrays = [], i, len;
for (i = 0, len = longArray.length; i < len; i += 1) {
    shortArrays.push(longArray.slice(i, i +1));
}

Following is the code example. I want to call array in this function:

var saveData = {
    teams: shortArrays,
}

I want ["Team 1","Team 2"],["Team 3","Team 4"] in shortArray. Your help will be much appreciated.

Upvotes: 0

Views: 583

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

You can use Array.splice which modifies by adding or removing the elements in array.

while(longArray.length) // make sure that array has something
      shortArrays.push(longArray.splice(0, 2)); // push the removed items

The Type Signature of Array.splice is

array.splice(start, deleteCount[, item1[, item2[, ...]]])

and it removes the first two elements in this case from the array, and returns it, which we push in the shortArrays.

Upvotes: 2

Related Questions