I have two arrays, available_items
and requested_items
. I want to remove elements from requested_items
that are missing in available_items
. Using forEach
does not give the expected result apparently because the internal index increments even when an element is deleted and the next element would have the old index.
Here's a test case (also in this jsbin):
var available_items = [2, 5, 9, 36, 48, 23];
var requested_items = [5, 12, 49, 30, 90, 17];
requested_items.forEach(function(v, i, a) {
if(available_items.indexOf(v) == -1) {
console.log("will remove " + i + ' ' + v);
a.splice(i, 1);
} else console.log("will keep " + i + ' ' + v);
});
console.log('Resulting request array is ' + requested_items.toString());
The result is:
"will keep 0 5"
"will remove 1 12"
"will remove 2 30"
"will remove 3 17"
"Resulting request array is 5,49,90"
This will be repeated tens of thousands times, so, using libraries (e.g. underscore), is something I want to avoid if they adversely impact performance.
So, my question is, what is the least expensive way to correct this?