0

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.

4
  • ["'Team 1', 'Team 2'"],["'Team 3', 'Team 4'"] is not the same as ["Team 1","Team 2"],["Team 3","Team 4"] - What should the output be exactly? Commented Sep 24, 2015 at 8:20
  • while Debugging it shows ["'Team 1'",""'Team 2'"] and i have to Pass ['Team1','Team 2'] Commented Sep 24, 2015 at 8:43
  • var bigData = { teams : [ ["'Team 1', 'Team 2'"],["'Team 3', 'Team 4'"], ], } This what the exact Format i need in shortArray Commented Sep 24, 2015 at 8:44
  • ["'Team 1'",""'Team 2'"] this is a syntax error. You really have to be more careful when posting information... Commented Sep 24, 2015 at 9:29

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Add one more bracket after splice(0, 2).
@RohilPatel there was a typo. I had typed in shortArray instead of shortArrays

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.