Home > Enterprise >  Duplicating array in nested array with one value change, changes entire nested array in javascript
Duplicating array in nested array with one value change, changes entire nested array in javascript

Time:07-25

I have an nested array. Example

let array = [['a','e1'],['b','b1']]

What i want to achive is a new nested array with a copy of one of the array's and a change to that copy.

when i run it though a loop (tried for and foreach) it duplicates the change throughout the entire nested array.

here is an example of the code (note its not key: index and just an example. the actual inside array contains 11 values in total)

let array = [['a','e1'],['b','b1']]

let result = []

for(let x of array){
    result.push(x);
    if(x[1]==='e1'){
        let newRow = x;
        newRow[1] = 'e2'
        result.push(newRow);
    }
}
//result: [[a,e2],[a,e2],[b,b1]]
let needResult = [['a','e1'],['a','e2'],['b','b1']]

Any assistance in this would be greatly appreciated.

Working example of the script : https://stackblitz.com/edit/js-ah1bvf?file=index.js

Thanks

CodePudding user response:

Instead of use let newRow = x;, as @tadman said in the comment you need to use another way like create a new array let newRow = []; //for example

let array = [['a','e1'],['b','b1'], ['c', 'e1']]

let result = []

for(let x of array){
    result.push(x);
    if(x[1]==='e1'){
        const newRow = [];
        newRow[0] = x[0];
        newRow[1] = 'e2'
        result.push(newRow);
    }
}
console.log(result)

CodePudding user response:

@tadman said in the comment let newRow = [...x] worked. I did not select @simons answer though valid as stated in my question the array can be quite large and i don't necessarily know exactly how long it is.

Thanks for the help!

CodePudding user response:

You have to deep copy that array try something like this

let newRow = JSON.parse(JSON.stringify(x))

So, your solution would be something like this

let array = [['a','e1'],['b','b1']]

let result = []

for(let x of array){
    result.push(x);
    if(x[1]==='e1'){
        let newRow = JSON.parse(JSON.stringify(x));
        newRow[1] = 'e2';
        result.push(newRow);
    }
}
console.log(result);

);

  • Related