Apologies I wrote my earlier question in a bit of a haste so couldn't phrase it properly with correct example.
The problem below has cropped up a number of times and I am always stuck. My knowledge of Javascript is beginner level only.
I want my array list to mutate and change while iterating over it. Essentially, iterating over the entirely new array gained from first iteration.
arr = [ 1, 2, 1, 3, 4, 2, 4, 1, 2, 4 ]
if arr[n]== 1 and arr[n+1] == 2 || arr[n] == 3 || arr[n+1] == 4
then remove arr[n] and arr[n+1] and current index is +2 else
newarr.push[n] and current index is +1
Loop over
After the above loop runs we get:
newarr = [1, 2, 4, 4];
Now loop runs over this new array with the same condition. We get
newarr = [4,4];
Now since the condition cannot be met, we break out of loop.
Hope this is clearer. I have tried everything but the loop always refers to the original array and I just do not know how to make it use the resulting array. Is this something that can be done by recursion or maybe the reduce method?
Any advice is appreciated. Thanks.
You can use recursion.
Everytime you call change_array()
you pass as argument the array that you want to be modified.
The first time you call this function you supply the original array. This function creates a new array,takes the needed elements from the old array and calls itself again with the new array as parameter.This continues until no more modifications are made to the array.
When you have a recursive function you should also have a condition that stops recursion to avoid infinite calls and stack overflows.
In this particular example if no modifications are made to the array, because no matching element was found according to our criteria, we stop recursion in this line
if(!found_element){ return false;}
Here is the full code
var original_arr = [ 1, 2, 1, 3, 4, 2, 4, 1, 2, 4 ];
change_array(original_arr);
function change_array(arr){
var temp_array=[];
var found_element=false;
console.log(arr);
for(let i=0;i<arr.length;i++){
if((arr[i]==1 && arr[i+1]==2 )|| (arr[i]==3 && arr[i+1]==4)){
found_element=true;
i++;
}else{
temp_array.push(arr[i]);
}
}
if(!found_element){ return false;}
change_array(temp_array);
}
when executed returns
[1, 2, 1, 3, 4, 2, 4, 1, 2, 4]
[1, 2, 4, 4]
[4, 4]