Home > Software design >  The if statement in the nested loop stops my function
The if statement in the nested loop stops my function

Time:01-10

I am writing a function which takes as first argument an array (arr1), and then N number of arguments (arr2), by which it removes the N arguments (arr2) from the array (arr1). The function seems to be doing the job, except it stops immediately when the if statement becomes true. I know this because if I remove the if statement the loops are iterated till the end. Any ideas what I did wrong?

So below the returned array should be ['A','B','E'].

const removeFromArray = function(arr1, arr2) {
    let arr_new = arr1;
    first_loop:
    for (const [y, elem] of arr1.entries()) {
        for (let i=1; i<arguments.length; i  ) {
            if ((elem === arguments[i])) {
                arr_new.splice(y);
            }
        }
    }
    return arr_new;
}

alert(removeFromArray(['A', 'B', 'C', 'D','E'],'C','D'));

CodePudding user response:

splice modify original array so when you call it. It just removes all elements from y until the end of arr_new and arr_new refers to arr1.

const foo = [1, 2, 3, 4];
foo.splice(2);
console.log(foo); // [1, 2]

arr1.entries() is an iterator which continue to track arr1 internally so when you modify arr1 it would modify entries too, so this is why your loop is stopped - there are no elements after splice

To fix this problem, you can modify your code

    if ((elem === arguments[i])) {
        arr_new.splice(y, /*           
  •  Tags:  
  • Related