2

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.

0

7 Answers 7

4

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(' ')));

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

1 Comment

Interesting…I expected this to be a little slow on large arrays with the unshift and splice, but it seems to run an order of magnitude faster than the other answers.
2

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; }

2 Comments

I'm sorry but why is there css in your answer?
@information_interchange just to expand the stack console.
2

You could move on each iteration last element from previous array to next one and if the last sub-array has more then 3 elements then remove the last one and add it to new array.

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

setInterval(function() {
  const last = arr.length - 1;
  const newElement = parseInt(Math.random() * 30)

  arr.forEach((a, i) => {
    if(i == 0) a.unshift(newElement);
    if(arr[i + 1]) arr[i + 1].unshift(a.pop())
    else if(arr[last].length > 3) arr[last + 1] = [arr[last].pop()]
  })

  console.log(JSON.stringify(arr))
}, 1000)

Comments

1

You can do this quite succinctly with a simple unravel/ravel. It easy to adjust group size too.

let arr = [ [1,2,3], [4,5,6], [7,8,9]]
let newEl = 0
let groupSize = 3

var newArr = [];
var unravelled = arr.reduce((a, c) => a.concat(c), [newEl])
while(unravelled.length) newArr.push(unravelled.splice(0,groupSize));

console.log(newArr)

Comments

0

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

function reassignChunk(x) {
  // create an array which will be used to store unwrapped values 
  var newArray = [];
  arr.forEach(function(elem) {
    newArray.push(...elem); //using spread operator to unwrap values
  });
  newArray.unshift(x, limit)
  var modArray = [];
  var m, j, temparray, chunk = 3;
  for (m = 0; m < newArray.length; m = m + limit) {
    // creatinging new array using slice
    modArray.push(newArray.slice(m, m + limit));
  }
  console.log(modArray)
}

reassignChunk(13, 3)
arr = [[i,1,2], [3,4,5], [6,7,8], [9]]

Comments

0

Assuming all your elements are numbers, you can do it like this:

  1. Prepend i to the array
  2. Flatten the array
  3. Convert the array to a comma-separated string
  4. Split the string into chunks of at most 3 numeric substrings (2 commas)
  5. Convert the chunks back into arrays of numbers

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

const i = 42;

const result = [i,...arr_1,...arr_2,...arr_3].join()
  .match(/(?:[^,]+(,|$)){1,2}[^,]*/g).map( x => x.split(',').map(Number) )
;

console.log( result );

Comments

0

You may do your 2d unshifting simply as follows;

var arr_1 = [1,2,3],
    arr_2 = [4,5,6],
    arr_3 = [7,8,9],
    arr   = [arr_1, arr_2, arr_3],
    us2d  = (a2d,...is) => is.concat(...a2d)
                             .reduce((r,e,i) => (i%3 ? r[r.length-1].push(e)
                                                     : r.push([e]), r), []);
console.log(JSON.stringify(us2d(arr,0)));
console.log(JSON.stringify(us2d(arr,-2,-1,0)));

Comments

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.