Home > Mobile >  Why is map changing my original array while iterating over?
Why is map changing my original array while iterating over?

Time:03-31

const z = [
    [
        "Almond",
        54
    ],
    [
        "Oats",
        75
    ],
    [
        "Raisins",
        undefined
    ]
]
let temp=[];
z.map((item, index) => {
    temp.push(item);
    if (item[item.length - 1] === undefined) {
      temp[index][1] = 'Not available'
    }
  });
console.log(temp)
console.log(z);

I'm changing the undefined entry to 'Not available' by creating another array. I'm not able to understand my z array is changing along with temp.

CodePudding user response:

A better approach would be to return a result array, mapping each entry in the item array to 'Not available' if it is undefined and then last entry in the item array.

This will leave the original z array untouched.

const z = [ [ "Almond", 54 ], [ "Oats", 75 ], [ "Raisins", undefined ] ]

let result = z.map((item, index) => {
    return item.map((val, idx) =>  {
        let notAvailable = (val === undefined) && (idx === item.length -1);
        return notAvailable ? 'Not available': val;
    })
})

console.log('z:', z);
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

For your example, spread operator would achieve what you want.

z.map((item, index) => {
    temp.push([ ...item]);
    if (item[item.length - 1] === undefined) {
      temp[index][1] = 'Not available'
    }
  });

Note: Spread operator deep copies the data if it is not nested. For nested data, it deeply copies the topmost data and shallow copies of the nested data.

  • Related