-2
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.

Neha Chaudhary
  • 1,071
  • 4
  • 15
  • 31
  • 4
    Because temp and z both hold references to the same arrays. – jonrsharpe Mar 31 '22 at 11:25
  • [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Andreas Mar 31 '22 at 11:27
  • 3
    You're also misusing `.map()`. Either use a `.forEach()` (or even better, a regular for-loop), or use `.map()` properly by returning the new element value and using the array returned by `.map()`. – Ivar Mar 31 '22 at 11:33
  • `const result = z.map(([product, stock]) => [product, stock ?? "Not available"])` I assume that the second element is the stock, but if it represents something else you can rename the parameter to whatever you want. – 3limin4t0r Mar 31 '22 at 11:48

1 Answers1

1

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; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40