1

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'],
]
1
  • What're you trying to do here? Can you explain the logic a little better? Commented Jan 6, 2020 at 14:45

2 Answers 2

1

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)

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

Comments

1

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

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.