Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays withing an array: how to push all elements forward by one with javascript

This is my array of arrays:

arr_1 = [1,2,3]
arr_2 = [4,5,6]
arr_3 = [7,8,9]

arr = [arr_1, arr_2, arr_3]
arr = [[1,2,3], [4,5,6], [7,8,9]]

What I want to do is push all elements like so that the final array is like the following and insert another element at the beginning of my array:

arr = [[i,1,2], [3,4,5], [6,7,8], [9]]

All sub-arrays must not be more than 3 elements.

Thanks for your help.

like image 796
Hugo Avatar asked Feb 13 '26 18:02

Hugo


2 Answers

You could visit all inner arrays and unshift the leftover values from the previous loop.

var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    chunk = 3,
    item = 'x',
    i = 0,
    temp = [item];
    
while (i < array.length) {
    array[i].unshift(...temp);
    temp = array[i].splice(chunk, array[i].length - chunk);
    i++;
}
if (temp.length) {
    array.push(temp);
}

console.log(array.map(a => a.join(' ')));
like image 59
Nina Scholz Avatar answered Feb 15 '26 08:02

Nina Scholz


You can use the function reduce

var arr = [[1,2,3], [4,5,6], [7,8,9]],
    newElem = "newOne",
    all = [newElem, ...arr.reduce((a, c) => [...a, ...c], [])], // All together
    // Build the desired output asking for the result of:
    // element mod 3 === 0
    result = all.reduce((a, c, i) => { 
      if (i % 3 === 0) a.push([c]);
      else a[a.length - 1].push(c);
      
      return a;
    }, []);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 26
Ele Avatar answered Feb 15 '26 08:02

Ele