Skip to content Skip to sidebar Skip to footer

Trying To Remove Items From An Array In Javascript/jquery

I've read several questions about this on StackOverflow, and found some solutions even, but they all seem to do the same weird thing: I have an array (array A) of 8 names: arrayA=

Solution 1:

You can use do..while loop, Array.prototype.splice() to remove elements from an array

arrayA= ["vincent"
        , "Rumpelstilzchen"
        , "LuckeR"
        , "Nordland"
        , "Siegfried"
        , "NeKrone"
        , "Carnage"
        , "tom59fr"];
arrayB= ["vincent"];

var i = 0;

do {
  if (arrayB[0] !== arrayA[i]) {
    arrayA.splice(i, 1);  
  } else {
  ++i;
  }
} while (i < arrayA.length);
delete i;

console.log(arrayA, arrayB);

Solution 2:

This is because when you call this:

arrayA= $.grep(arrayA, function(value) {
  return value != removeName;
});

The length of arrayA changes, thus arrayA[k] will move to the position of arrayA[k-1] (when k>i).

So we'd better create a new array to store the filtered items and after the iteration, give its value to arrayA.

arrayA= ["person1", "person2", "person3", "person4", "person5", "person6", "person7", "person8"];
arrayB= ["person1","person4"];
var arrayC=[];
for (var i = 0, len = arrayA.length; i < len; i++) {
  console.log('inArray:'+$.inArray(arrayA[i], arrayB))
  if($.inArray(arrayA[i], arrayB) != -1){
    arrayC.push(arrayA[i]);
  }
  console.log('arrayC now consists of: ' + arrayC);
}
arrayA=arrayC;
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Post a Comment for "Trying To Remove Items From An Array In Javascript/jquery"