Home > OS >  Why javaScript nested map() doesn't return the value as intended?
Why javaScript nested map() doesn't return the value as intended?

Time:10-19

I was doing this problem in leetcode when javascript map() method was not working as intended. The question is as follows.

Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.

To flip an image horizontally means that each row of the image is reversed.

For example, flipping [1,1,0] horizontally results in [0,1,1]. To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.

For example, inverting [0,1,1] results in [1,0,0].

So I got the result as follows,

const flipAndInvertImage = function (image) {
    const flippedImage = flipImage(image);
    return invertImage(flippedImage);
};

function flipImage(image){
    image.map(rows => {
        return rows.reverse();
    })
    return image;
}

function invertImage(image) {
    image.map(row => {
        row.map((num,index,array) => {
            array[index] =  (num === 0 ? 1 : 0)
        })
        return row;
    })
    return image;
}

But why is that nested row.map doesn't return the value directly when I try it like this?

const invertImage = (image) => {
    image.map(row => {
        row.map((num,index,array) => {
            return (num === 0 ? 1 : 0)
        })
        return row;
    })
    return image;
}

Or like this?

const invertImage = (image) => {
    image.map(row => {
        row.map((num,index,array) => {
            let col = (num === 0 ? 1 : 0)
            return col;
        })
        return row;
    })
    return image;
}

Am I doing something wrong here?

CodePudding user response:

map always returns a new array, and you are not explicity returning the second map. Like:

const invertImage = (image) => {
image.map(row => {
//return here
   return row.map((num,index,array) => {
        let col = (num === 0 ? 1 : 0)
        return col;
    })
    
})
return image;

}

CodePudding user response:

Array.map doesn't mutate the given Array. So you need to either assign the result of Array.map to a variable and return said variable, or directly return the result. E.g:

const invertImage = (image) => {
    return image.map(row => {
        return row.map((num,index,array) => {
            let col = (num === 0 ? 1 : 0)
            return col;
        })
    })
}

OR

const invertImage = (image) => {
    const flippedImage = image.map(row => {
        const flippedRow = row.map((num,index,array) => {
            let col = (num === 0 ? 1 : 0)
            return col;
        })
        return flippedRow;
    })
    return flippedImage;
}

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The map() method >>>creates a new array<<< populated with the results of calling a provided function on every element in the calling array.

  • Related