I have an array JavaScript and a string :
var pool1 = ['ca','cahier','cartable','carte','cartographe','canape'];
var key1 = 'car';
What I am trying to do is, remove from the array all value that aren't containing key1.
To do so I've written this function :
function searchInPool(key, pool){
for (i = 0; i < pool.length; i++) {
var index = pool[i].indexOf(key);
if (index > -1) {
pool.splice(index, 1);
}
}
return pool;
}
It seems to be working, except that the final result gives me :
["cartable", "carte", "cartographe", "canape"]
It has succesfully removed caand cahier but canape shouldn't be here since it doesn't contain car anyone can explain me what I've misunderstood from what I've written in my function ?
The final result expected is :
["cartable", "carte", "cartographe"]
Thanks a lot
for (var i = pool.length - 1; i >= 0; i--) {because this way you'll account for the shortening length of the array which isn't happening in your example.splice()withindex, which is the position ofkey1in the string. It seems wrong to me.poolwhile you are looping over it, which gives your strange results and 2) the index you use to remove an item is the index where your code finds the stringcar, and it should be the index of the item in the array and 3) the check(index > -1)actually tries to remove items that DO havecarin them. It is reallyt pure luck that the other two items are removed correctly and that the right items stay in.