Convert two forEach into map

Viewed 417

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]

4 Answers

You can use array#map and array#concat to generate the desired array.

var storedNames = [1,2,3],
    mod = {id: 3, blocList: [{id:11}, {id:12}]},
    result = [...storedNames].concat(mod.blocList.map(({id}) => id));
console.log(result);

You could use map in combination with spread syntax, like this:

var storedNames = [1,2,3];
var mod = {id: 3, blocList: [{id:11}, {id:12}]};

if (storedNames.some(item => item == mod.id)) {
    storedNames.push(...mod.blocList.map(bloc => bloc.id));
}

console.log(storedNames);

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);
    })
  }
})

You can also try below code. Here I have just tried to obtain the output that you want.

If you have more data with different forms then in that case you will need to modify the code based on your target result.

Note: Here you are using Typescript and my answer is in pure JavaScript (Node.js), so please do not forget to specify the type of variables in parameter-list or in initialization statements like function(item){...} to function(item: number){...} etc.

var storedNames = [1,2,3];
var mod = {id: 3, blocList: [{id:11}, {id:12}]};

var storedNames = storedNames.map(function(item) {
    if(item === mod.id) {
        var bArr = [item]; // [3]
        var cArr = mod.blocList.map((bloc) => {
            return(bloc.id); // Returning 11 and 12 one after one
        });

        bArr = bArr.concat(cArr);
        // console.log(cArr); /* [ 11, 12 ] */
        // console.log(bArr); /* [ 3, 11, 12 ] */
        return bArr;
    }
    return item; // Returning 1 and 2 one after one
}) 

console.log(storedNames);  // [ 1, 2, [ 3, 11, 12 ] ]

//Finally
storedNames = storedNames.concat(storedNames.splice(storedNames.length - 1, 1)[0]); 

console.log(storedNames); // [ 1, 2, 3, 11, 12 ]
Related