js delete a number of different elements specified

Problems encountered in a pen questions, as from an array [5,1,6,8,2,4,5,10], delete another array appears [5,6,2,10] in the elements, and only deleted from left to right 1st like elements, the result is deleted [1, 8, 4, 5], which leads to the following problems.

Delete the same element multiple

use filter

var ARR = [1,1,1,2,2,2,3,3 ];
 // delete the element 2 is 
arr = arr.filter (item => item == 2!);

Use of reverse circulation or circulation for forEach iterate words, in the method of the internal splice member are not the correct result, solution is to use a reverse cycle

var arr = [1,2,3,1,2,3];
for (let i = arr.length - 1; i >= 0; i--) {
    if (arr[i] === 2) {
        arr.splice(i, 1);
    }
}

Using regular

    var ARR = [. 1,. 1,. 1, 2, 2, 2,. 3,. 3 ];
     var A = 2 ;
     // use the template string can be passed into the variable 
    var REG = new new the RegExp ({A} $ ``, " G " ); 
    ARR = arr.join ( " ") .replace (REG," ") .split (" ") Map (I => Number The (I.))

Delete multiple different elements

use filter

ARR = var [1,1,1,2,2,2,3,3 ]; 
// delete elements 2 and 3 is 
arr = arr.filter (item => [ 2,3] .indexOf (item) = = -1);

Use of reverse circulation

ARR = var [1,2,3,1,2,3 ]; 
for (I = the let arr.length -. 1; I> = 0; i-- ) { 
// delete the element is 2,3 IF ([ ! 2,3] .indexOf (ARR [I]) == -1 ) { arr.splice (I,. 1 ); } }

Using regular

    var ARR = [. 1,. 1,. 1, 2, 2, 2,. 3,. 3 ];
  // delete the element is 2,3 
    var A = 23 is ;
     // use the template string can be passed into the variable 
    var REG = new new the RegExp ( `[$ {A}]`, "G" ); 
    ARR = arr.join ( ""). Replace (REG, "") .split ( "") Map (I => Number The (I)).;

Return to the topic

Currently only think of the method of use filter, reverse circulation and regular way I did not expect, welcome to add.

var ARR = [1,1,1,2,2,2,3,3 ];
 // removes the first element is 2,3 
var arr2 is = [2,. 3 ]; 
ARR = arr.filter (Item = > {
     IF (arr2.indexOf (Item) == -1! ) { 
      arr2.shift (); 
      return  to false 
    } the else {
       return  to true 
    } 
});

I hope you valuable advice.

Guess you like

Origin www.cnblogs.com/Ingots/p/11333727.html