Hi,
I wonder if there any better method to check if the element in array B exists in array A, then remove it from array A.
var arrA = ['a','b','c','d','e']
var arrB = ['c'];
I copied and modified this code from somewhere I got it online, but not sure if I understand it as it has two for-loops in it…
for(var i=0;i<arrA.length;i++) {
for(var j=0;j<arrB.length;j++) {
if(arrB[j] == arrA[i]) {
var index = arrA.indexOf(arrA[i]);
}
}
}
code to remove element from array A,
if(index >= 0){
arrA.splice(index,1);
alert(arrA.join(" "));
}
Many thanks,
Lau
mrhoo
March 1, 2010, 6:38pm
2
All modern browsers except IE have a useful method to find an item in an array by its value- You can add it to IE without changing the others,
it will come in handy again and again.
Array.prototype.indexOf=
Array.prototype.indexOf || function(what, index){
index= index || 0;
var L= this.length;
while(index< L){
if(this[index]=== what) return index;
++index;
}
return -1;
}
This method removes each of its arguments, if present, from the original array
Array.prototype.remove= function(){
var what, L= arguments.length, ax;
while(L && this.length){
what= arguments[--L];
while((ax= this.indexOf(what))!= -1){
this.splice(ax, 1);
}
}
return this;
}
to remove all of the elements of one array from another, apply the method:
var a1=[1,2,3,4,5,6], a2=[5,6,7,8,9];
a1.remove.apply(a1,a2);
returned value: (Array) [1,2,3,4];
mrhoo:
All modern browsers except IE have a useful method to find an item in an array by its value- You can add it to IE without changing the others,
it will come in handy again and again.
Array.prototype.indexOf=
Array.prototype.indexOf || function(what, index){
index= index || 0;
var L= this.length;
while(index< L){
if(this[index]=== what) return index;
++index;
}
return -1;
}
This method removes each of its arguments, if present, from the original array
Array.prototype.remove= function(){
var what, L= arguments.length, ax;
while(L && this.length){
what= arguments[--L];
while((ax= this.indexOf(what))!= -1){
this.splice(ax, 1);
}
}
return this;
}
to remove all of the elements of one array from another, apply the method:
var a1=[1,2,3,4,5,6], a2=[5,6,7,8,9];
a1.remove.apply(a1,a2);
returned value: (Array) [1,2,3,4];
hi, not sure if I understand this code but thanks a lot!