How to convert this two loops forEach into map function?
var storedNames = [1,2,3];
var mod = {id: 3, blocList: [{id:11}, {id:12}]};
storedNames.forEach((item: number) => {
if (item === mod.id) {
mod.blocList.forEach((bloc: Bloc) => {
storedNames.push(bloc.id);
});
}
});
The result will be: storedNames = [1, 2, 3, 11, 12]
This will work, but it is not a perfect use of Array.map(). Ideally, you'd use map if you want to keep the storedNames intact and create a copy of it with the changes that loop makes. Such as:
modifiedStoredNames = storedNames.map(//do stuff);
To my understanding, map is a way of making a copy of an array with the modifications applied for each elements using the function passed as parameter. In this case, we're just using map() to loop (two loops to be precise) and updating the array storedNames based on a condition within that loop. And ignoring what map really returns.
storedNames.map((item: number) => {
if (item === mod.id) {
mod.blocList.map((bloc: any) => {
storedNames.push(bloc.id);
})
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With