Help needed. if statement in forEach()

how do I write this loop as forEach() method.

for (let i = 0; i < arr2.length; i++){
       if (itemCheck(arr2[i], arr1)){
          arr1.push(arr2[i]);
       }
    }

Are you familiar with forEach at all? If not, I would recommend you first read the documentation and then give it a try. If after trying you can’t get it to work then you can show us what you have and we can offer some suggestions.

@bbsmooth
itemCheck is suppose to return a Boolean.
I just read on stackflow.com forEach() should be used where side effects are expected. But in itemCheck that side effect is dependent on that ‘if’.

you can have an if statement in the callback of forEach

@ilenia
I get that.
actually i was advised to use methods instead of loops.
so can i do this.

array.forEach(element => { if (functinon(element, array2)) { /modification } });

you are not using a loop there, are you?

Have you tried it? Again, give it a try and if you can’t get it working then show us what you have so far and we can offer suggestions. Don’t be afraid to experiment and make mistakes. That’s how you learn.

@bbsmooth you saw it yesterday. I am trying to improve it. can u suggest where to use array methods instead of loops.

function updateInventory(arr1, arr2){
    //Function to check if new item is present in current inventory if yes then update current inventory.
    function itemCheck(a, b){
        let result = true;
     for (let j = 0; j < b.length; j++){
        if (b[j].includes(a[1])){
            b[j][0] += a[0];
           result = false;
        }
     }
        return result;
    }
    // Compare function to arrange alphabetically.
    function compareFunction (a, b){
      return  a[1] === b[1] ? 0: a[1] < b[1] ? -1: 1;
    }

    //Update current inventory
    for (let i = 0; i < arr2.length; i++){
       if (itemCheck(arr2[i], arr1)){
          arr1.push(arr2[i]);
       }
    }
    //Alphabetical order.
    arr1.sort(compareFunction);
    return arr1;
 }

If you are using a for loop to iterate through an array then you can usually change that to a forEach. I thought this is what you were trying to do in the first place? If so, then I suggest you try it. If you can’t get it to work then you can show us what you have and we can offer suggestions.

I don’t mean to be rude but at some point you have to stop thinking about it and just do it :slight_smile:

try it

arr2.forEach(item => itemCheck(item, arr1) && arr1.push(item));

FYI, we try not to just give people the answers but rather guide them to discovering the answer for themselves. If you do feel the need to post a solution then I think you are supposed to wrap it in spoiler tags so they can choose whether they want to look or not.

[spoiler]

   ... the solution ...

[/spoiler]

@bbsmooth hi, I tried it. and its working.

function updateInventory(arr1, arr2){
    let curInventory = [...arr1];
    let newInventory = [...arr2];

 let itemUpdate = function(a, b){
     let result = true;
     b.forEach(item => {
         if (item.includes(a[1])){
             item[0] += a[0];
             result = false;
         }
     });
     return result;
 };

 function compareFunction(a, b){
     return a[1] === b[1] ? 0: a[1] < b[1] ? -1: 1;
 }

    newInventory.forEach(element => {
        if (itemUpdate(element, curInventory)){
                curInventory.push(element);
        }
    });
    curInventory.sort(compareFunction);
    return curInventory;
}


// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

const a = updateInventory(curInv, newInv);
console.log(a);
console.log(curInv);

But now, as I did this. let curInventory = [...arr1]; as per my understanding curInv should not mutate.
I think I understand it wrong. Can you please explain it too.
And thanks for your patience.

That is correct. You pass curInv into compareFunction() (as arr1) and the first thing you do is make a copy of it:

let curInventory = [...arr1];

And you only work on curInventory in the function, so arr1 is never changed and thus curInv is not mutated. The two console.logs at the end prove this.

curInv is a multidimensional array, the way you made a cooy works only with monodimensional array, you are changing the nested arrays as those are not copied

Oh Okay, Sure, I will keep this principle in mind for next time. Thanks.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.