Remove elements in the array [JavaScript]

Question (1)
Remove all elements in the array arr whose value is equal to item. Do not modify the array arr directly, and the result will return a new array.
Example 1
Input
[1, 2, 3, 4, 2], 2
Output
[1, 3, 4]
Question (2)
Remove all values ​​in the array arr that are equal to item The elements of, operate directly on the given arr array and return the result.
Example 1
Input
[1, 2, 2, 3, 4, 2, 2], 2
Output
[1, 3, 4]

The requirements of these two questions are different. One requires the output as a new array, and the other requires modification in the original array.
Problem one solution:

function remove(arr, item) {
    
    
    var sum=[];
    for(var i=0;i<arr.length;i++){
    
    
        if(arr[i]!=item){
    
    
          sum.push(arr[i]);
        }
    }
    return sum;
}

Problem two solution:


function removeWithoutCopy(arr, item) {
    
    
    var n=arr.length;
     for(var i=0;i<n;i++){
    
    
         if(arr[0]!==item)   
             arr.push(arr[0]);
         arr.shift();    
    }
    return arr;
}

There is nothing to say about topic one, just use the push method proficiently. The solution for topic two is more clever. Push the different item at the end of the array, and then use shift to delete the first element, which is equivalent to filtering the array.

Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/104923652