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= ["person1", "person2", "person3", "person4", "person5", "person6", "person7", "person8"];
And I have an array (array B) of 1 name:
arrayB= ["person1"];
Now, I want to remove all names that do not occur in Array B, from Array A.
So I wrote a little function which loops through all items in Array A, and checks if they occur in Array B. If they do not, I remove them from Array A.
So I looked for a function to remove strings from an array (in PHP, this is all so much easier...), and I found several methods, which all give me exactly the same problem. In the example below, I chose the cleanest method, using jquery's $.grep:
arrayA= ["person1", "person2", "person3", "person4", "person5", "person6", "person7", "person8"];
arrayB= ["person1"];
for (var i = 0, len = arrayA.length; i < len; i++) {
if($.inArray(arrayA[i], arrayB) == -1){
var removeName= arrayA[i];
console.log('Removing row of: ' + removeName);
/*
$('tr[player=\'' + removeName + '\']').find('td')
.wrapInner('<div style="display: block;" />')
.parent()
.find('td > div')
.slideUp(700, function(){
$(this).parent().parent().remove();
});
*/
arrayA= $.grep(arrayA, function(value) {
return value != removeName;
});
console.log('arrayA now consists of: ' + arrayA);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As you can see, it only removes the "even" items from arrayA, i.e. "person2", "person4", "person6" and "person8".
If I execute this function multiple times, the 2nd time it removes again only the "even" items (which is now "person3" and "person7"), and the third time, it removes "person5" (finally)...
Can someone please tell me what I'm not seeing? You can see from the console log that, the first time you run it, all the "odd" items in the array, (i.e. person3, person5 and person7) are "undefined"...
forloop? Is requirement to remove elements from original array or return new array having only elements that are withinarrayB?arrayAshould become as["person1"]after filtering? What is the benefit? eventuallyarrayAandarrayBwill become equal. What's the point?arrayBof ones that are inarrayA, and save that toarrayA...arrayA = arrayB.filter(function(s) { return arrayA.includes(s) })