Search code examples
javascriptjqueryarraysmultidimensional-arrayremoveall

jQuery/Javascript removing an object from array of objects


I have an array of objects which looks like this:

[
[0]{"asin": "1234",
    "title: "Test"},
[1] {"asin": "123fef4",
    "title: "aaaaaaa"},
[2] {"asin": "testtet",
     "title: "testt123"},
]

Adding the items to the array works like a charm and here is the code:

 items.push(
 {
   "asin": "1234",
   "title": "test"
 });

This part works okay... Now here comes the part where I need to remove the items frmo the array by ASIN property inside of it...

I have a function which looks like this:

  function remove(array, element) {
            const index = array.indexOf(element);
            array.splice(index, 1);
            console.log("Removed element: " + element);
        }

How I call the remove function:

  remove(items, "1234");

This removes the item from the list, but not the one that I want.. I checked when I pass value 1234, the item with asin value 1234 stays in the array...

What could be wrong here ? :/


Solution

  • You can't match a string against an object. Use findIndex like below and use the returned index.

    function remove(array, element) {
        const index = array.findIndex(e => e.asin === element);
        array.splice(index, 1);
        console.log("Removed element: " + element);
    }