Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  106] [ 1]  / answers: 1 / hits: 120815  / 8 Years ago, fri, january 27, 2017, 12:00:00

In this code I want to remove an element from the cart_products array.



var cart_products = [17^1, 19^1, 18^1];
var product = 17;

$.each(cart_products,function(key, item) {
if(item.indexOf(product+^) !== -1){
cart_products.splice(key, 1);
}
});


But I get this error in Google Chrome console:




Uncaught TypeError: Cannot read property 'indexOf' of undefined




Is there something wrong with the code?



Thanks for your help.


More From » jquery

 Answers
27

The problem is that you're modifying the array while jQuery's $.each is looping over it, so by the time it gets to the end, the entry that used to be at index 2 is no longer there. (I admit I'm a bit surprised $.each behaves that way, but I haven't used $.each in at least five years, so...)



If the goal is to remove matches from the array, the better choice is filter:





var cart_products = [17^1, 19^1, 18^1];
var product = 17;

cart_products = cart_products.filter(function(item) {
return item.indexOf(product+^) === -1;
});
console.log(cart_products);





...or alternately if it's important to modify the array in-place rather than creating a new one use a boring for loop as Andreas points out looping backward through the array so it doesn't matter when you remove things:





var cart_products = [17^1, 19^1, 18^1];
var product = 17;

var target = product + ^;
for (var index = cart_products.length - 1; index >= 0; --index) {
if (cart_products[index].indexOf(target) !== -1) {
cart_products.splice(index, 1);
}
}
console.log(cart_products);




[#59182] Wednesday, January 25, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hayleevalenciac

Total Points: 164
Total Questions: 89
Total Answers: 106

Location: Burkina Faso
Member since Thu, Dec 15, 2022
2 Years ago
;