简体   繁体   中英

Only last element from the array gets concatenated in every loop

Issue: Only the last element of the array is getting concatenated in finalOutput in a loop

 let listA = [ [1, 2], [7, 8], [4, 5], [11, 12] ]; let listB = [ ['x', 'y', 'z'], ['d', 'd', 'd'], ['f', 'y', 's'] ]; let finalOutput = []; for (let i = 1; i <= listA.length - 1; i++) { let dataIndx = 0; for (let item of listB) { if (item[1] !== 'd') { item[1] = listA[i][dataIndx]; dataIndx++; } } finalOutput = finalOutput.concat(listB); } console.log('Undesired output:', finalOutput);

Currrent undesired output:

[
    ['x', '11', 'z'], ['d', 'd', 'd'], ['f', '12', 's'],
    ['x', '11', 'z'], ['d', 'd', 'd'], ['f', '12', 's'],
    ['x', '11', 'z'], ['d', 'd', 'd'], ['f', '12', 's'],
]

Expected finalOutput value to be

[
    ['x', '7',  'z'], ['d', 'd', 'd'], ['f', '8',  's'],
    ['x', '4',  'z'], ['d', 'd', 'd'], ['f', '5',  's'],
    ['x', '11', 'z'], ['d', 'd', 'd'], ['f', '12', 's'],
]

The problem here is that you iterate through listB several times and modify that list every time (referene to the same array). Since array is a reference the last one will be caputered in your result set. Try to clone listB instead:

 let listA= [[1,2],[7,8],[4,5],[11,12]]; let listB= [['x','y','z'],['d','d','d'],['f','y','s']]; let finalOutput = []; for (let i = 1; i <= listA.length - 1; i++) { let dataIndx = 0; let listBB = listB.map(x => ([...x])); // "cloning an array of arrays" for(let item of listBB){ if (item[1] !== 'd') { item[1] = listA[i][dataIndx]; dataIndx++; } finalOutput = finalOutput.concat(listBB); } } console.log(finalOutput)

You could slice the first array and take a flatMap for the nested array.

 let listA = [[1, 2], [7, 8], [4, 5], [11, 12]], listB = [['x', 'y', 'z'], ['d', 'd', 'd'], ['f', 'y', 's']], result = listA .slice(1) .flatMap(([v]) => listB.map(([a, b, c]) => [a, b === 'd' ? b : v, c])); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM