Imagine we have an array with 3 arrays inside and each element is a 7-element-array. (like arr[3][7]) I want to transfer these elements to a new array like arr2[3][1][7]. I tried foreach method and it copies the last nested array to all new elements.
var c3 = new Array(players).fill(new Array(1).fill(new Array(7)))
// console.log(c2)
// c2= [
// [x1, x2, x3, x4, x5, x6, x7],
// [y1, y2, y3, y4, y5, y6, y7],
// [z1, z2, z3, z4, z5, z6, z7]]
c2.forEach(function (val, ind) {
c3[ind][0] = c2[ind]
})
// it supposed to return c3:
// [
// [[x1, x2, x3, x4, x5, x6, x7]],
// [[y1, y2, y3, y4, y5, y6, y7]],
// [[z1, z2, z3, z4, z5, z6, z7]]]
// But it returns:
// [
// [[z1, z2, z3, z4, z5, z6, z7]],
// [[z1, z2, z3, z4, z5, z6, z7]],
// [[z1, z2, z3, z4, z5, z6, z7]]]
CodePudding user response:
Something like this ?
const data = [
['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7'],
['y1', 'y2', 'y3', 'y4', 'y5', 'y6', 'y7'],
['z1', 'z2', 'z3', 'z4', 'z5', 'z6', 'z7'],
];
const res = data.map(v => [v]);
console.log(res);
CodePudding user response:
I hope this helps
function flatten(array){
const res = [];
for(let i = 0; i< array.length; i ){
if(Array.isArray(array[i])){
const flat = flatten(array[i])
for(let j = 0; j < flat.length; j ){
res.push(flat[j])
}
}else{
res.push(array[i])
}
}
return res
}
console.log(flatten( [ [1], [[2],[3]], [[[[4]]]]] ))
output // [1, 2, 3, 4]