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;
CodePudding user response:
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)
CodePudding user response:
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);
};
});
CodePudding user response:
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}
