0

I have an array filled with fridge items. I am trying to find the index of particular items and then splice them out of the array and then return the item and console.log the remaining items in the fridge. I have no clue why it isn't working. I have tried several different variations and I have tried looking at other similar answers for this question. Any advice or help is much appreciated.

fridge = ["milk", "cheese", "butter"];

function removeItemFromFridge(item) {
  
  if (item.indexOf()) {
    fridge.splice(item);
    return item;
  } else {
    return null;
  }
}
removeItemFromFridge("milk");
removeItemFromFridge("butter");

console.log(fridge);
  • 2
    `if (item.indexOf()) {`?? Shouldn't it be `if (fridge.indexOf(item)) {`?? This will not solve this, there are more issues.. – rahulpsd18 Jan 19 '21 at 15:36
  • You can use `filter` method of Array to remove a specific item. – Ihor Tkachuk Jan 19 '21 at 15:37
  • @IhorTkachuk, of course, technically, `filter` doesn't remove an item from an array, it creates a new array. – Wyck Jan 19 '21 at 15:38
  • 1
    @Wyck But, modifying outer scope is bad practice. – Ihor Tkachuk Jan 19 '21 at 15:40
  • Does this answer your question? [How can I remove a specific item from an array?](https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array) – Wyck Jan 19 '21 at 15:42

2 Answers2

1

If fridge is a value we can replace entirely instead of modifying the existing array, you can use array.filter() instead.

function removeItemFromFridge(item) {
  fridge = fridge.filter(v => v !== item)
}

Otherwise, if you do want to preserve that same array, you can find the item index and splice it off.

function removeItemFromFridge(item) {
  const index = fridge.indexOf(item);
  if (index !== -1) fridge.splice(index, 1)
}

Also, doing a return is not needed since your caller isn't using the returned value.

Joseph
  • 107,072
  • 27
  • 170
  • 214
0

indexOf finds the first index that matches the given value in the array, if no such value is present it returns -1. for splice you specify the first index from where you want to start deleting and in the second argument you pass the number of element you want to delete starting from given index in first argument. I think you want to do it like this way

let fridge = ["milk", "cheese", "butter"];

function removeItemFromFridge(item) {
  const index = fridge.indexOf(item);
  
  if (index > -1 ) {
    fridge.splice(index, 1);
    return item;
  } else {
    return null;
  }
}
removeItemFromFridge("milk");
removeItemFromFridge("butter");

console.log(fridge);
mss
  • 1,228
  • 1
  • 7
  • 16