简体   繁体   中英

Use Array.map on an 2-dimensional Array

So I have a 2-dimensional Array and want to use a "randomBool" function on each of the elements of the elements in the array.

The "randomBool" function just returns a random boolean:

const randomBool = () => Boolean(Math.round(Math.random()));

this would be the 2-dimensional Array, that I would input:

var test = [
    ["just","some","random","text"],
    [1412,"test",1278391]
]

There is a working for-loop nested in a for-loop:

for (let el of test){
    for(let i in el){
        el[i] = randomBool();
    }
}

I tried this:

test.forEach(el => el.map(el2 => randomBool()));

But it didn't work. Why?

You need to use two nested maps.

const randomBools = test.map(outer => outer.map(inner => randomBool()))

forEach is usually intended to iterate over each item in order to perform some kind of side effect without returning anything and without mutating the original array. For example, printing each item to the console.

map , on the other hand, is intended to take an array and return a new array of the same size, with the values transformed in some way, without mutating the original array. For example, uppercase all the words in a list.

Since you want to return a new 2 dimensional from your existing 2 dimension array with some data transformed, you need to nest your map functions. This will map first over the rows (outer), then the columns (inner). The results of the inner maps will be collected into the outer map and you'll be left with a 2 dimensional array with your new values, all without modifying the original array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM