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

2
  • 1
    Cause an object does not match a string?!?!? Commented Jun 4, 2018 at 16:17
  • @JonasW. Ok got it but how can I fix it ? :) Commented Jun 4, 2018 at 16:18

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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");

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.