'Javascript TypeError: Cannot read property 'indexOf' of undefined

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.



Solution 1:[1]

First of all, you don't need to use a jQuery each for this. Second, it's not a great idea to alter an array that you are operating on. If you're trying to remove elements from an array, use filter. Filter has the following signature:

someArray.filter(function(item, index, array) {
  // return a value that is truthy to keep an item or falsey to remove it
})

Filter returns a new array with only the values that match what you want. That means you don't mess with your original array, which is a good idea anyways. In your case it would look like this:

var filteredProducst = cart_products.filter(function(item) {
  return item.indexOf(product + "^")
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shadymoses