0

I have this simple JS array:

var myStringArray = ['item1','item2','item3','item4','item5','item6','item7','item8','item9','item10','item11','item12','item13','item14','item15','item16','item17'];

I would like to format the data from the array so that it looks like this:

[
    ["item1","item2","item3"],
    ["item4","item5","item6"],
    ["item7","item8","item9"],
    ["item10","item11","item12"],
    ["item13","item14","item15"],
    ["item16","item17"]
]

The line breaks don't matter - but that's the format I'm trying to get to.

I've got this far:

var myCols = 3;
var myStringArray = ['item1','item2','item3','item4','item5','item6','item7','item8','item9','item10','item11','item12','item13','item14','item15','item16','item17'];  
var arrLen = myStringArray.length;      
var output = "[";

for (var i=0, l=myStringArray.length; i<l; i++) {

  var this_loop = i+1;
  var this_item = myStringArray[i];
  var this_mod = (i % myCols) + 1;

  console.log(this_item + '__' + i + '______' + this_mod);

    if (this_mod == 1) {
        output += '[';
    }

    if (this_mod == 3 && this_loop < arrLen) {
        output += '],';
    }

    if (this_loop === arrLen) {
        output += ']';
    }

}   

output += ']';

console.log (myStringArray);
console.log (arrLen);
console.log (output);

I'd like to be able to control the number of "columns" - or items per set of square brackets, hence the myCols variable.

The output from the above generates the correct sequence of square brackets (line breaks added by me afterwards):

[
    [],
    [],
    [],
    [],
    [],
    []
]

The thing I'm struggling with is working out the logic to populate each set of square brackets with the sequences of items from the array.

Any advice much appreciated.

Thanks

4532066
  • 2,042
  • 5
  • 21
  • 48

1 Answers1

1

Try this :

var newArr = [];
var myStringArray = ['item1','item2','item3','item4','item5','item6','item7','item8','item9','item10','item11','item12','item13','item14','item15','item16','item17'];

for (var i = 0; i < myStringArray.length; i+=3) {
    newArr.push(
        myStringArray.slice(i, i+3)
    );
}

console.log(JSON.stringify(newArr, null, 4));
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223