1

I have a situation where I get the data in an array and I have to convert that to multiple arrays... Like Matrix.

const array = [1,2,3,4,5,6,7,8,9]

the output should be:

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

this is what I have so far:

let i = 0;
const add = [];
while (i < list.length) {
  add.push([list[i], list[i + 2]]);
  i = i + 1;
}
return add;
3
  • Does this answer your question? How to create array from multiple array objects in single array object? Commented Jan 21, 2022 at 4:35
  • no, they have multiple arrays and they are putting in one array. Mine is the opposite. Commented Jan 21, 2022 at 4:40
  • @jakasJakas, post an answer. check if it works for you! Commented Jan 21, 2022 at 4:46

4 Answers 4

2

I think this will be able to solve your problem.

    function chunkArrayInGroups(arr, size) {
    let newArr = [];
    for (let i = 0; i < arr.length; i += size) {
        newArr.push(arr.slice(i, i + size));
    }
    console.log(newArr)
    return newArr;
}
chunkArrayInGroups([1,2,3,4,5,6,7,8,9],2)

This will divide our larger array into chunk array of size 2 less than 2.

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

1 Comment

Your code returns in sequence order. If you check my question I need in this format: [[1,3],[2,4],[5,7],[6,8],[9]]
0

Maybe try this one?

let i = 0;
const list = [1,2,3,4,5,6,7,8,9]
const add = [];
let newarr =[]
while (i < list.length) {
  add.push([list[i], list[i + 2]]);
  add.push([list[i+1],list[i+3]])
  i +=4;
}
//remove undefined item from the array
newarr = add.map(arr=>arr.filter(item =>item != undefined)).filter(item=>item!="")


console.log(newarr)

Comments

0
const array = [1,2,3,4,5,6,7,8,9];
const visitedIndex = [];
const newArray = [];
array.forEach((element, i) => {
  if (!visitedIndex.includes(i)) {
    if (array[i+2]) {
      newArray.push([array[i], array[i+2]])
    } else {
      newArray.push([array[i]])
    }
    visitedIndex.push(i);
    visitedIndex.push(i+2);
  };

});

Comments

0

Lodash chunk if you don't mind.

Or you can use recursive approach in vanila js.

const array = [1,2,3,4,5,6,7,8,9];

const chunk = (arr, n) => arr.length ? [arr.slice(0, n), ...chunk(arr.slice(n), n)] : [];

console.log(chunk(array, 2));
.as-console-wrapper{min-height: 100%!important; top: 0}

1 Comment

Your code returns in sequence order. If you check my question I need in this format: [[1,3],[2,4],[5,7],[6,8],[9]]

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.