0

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 ? :/

User987
  • 3,663
  • 15
  • 54
  • 115

3 Answers3

1

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);
}
baao
  • 71,625
  • 17
  • 143
  • 203
0

You may wanna extend your removal function to:

function remove(array, key, value) {
  const index = array.findIndex(el => (el[key] || el) === value);
        array.splice(index, 1);
        console.log("Removed: " + index);
}

So you can do

remove(items, "asin", "1234");
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Try the following:

var arr =[
{"asin": "1234",
"title": "Test"},
{"asin": "123fef4",
"title": "aaaaaaa"},
{"asin": "testtet",
"title": "testt123"},
];

function remove(arr, val){
  var index = arr.findIndex((o)=> o.asin === val);
  if(index != 1)
    arr.splice(index, 1);
}
remove(arr, "1234");
console.log(arr);
amrender singh
  • 7,949
  • 3
  • 22
  • 28