简体   繁体   中英

Removing an item from an array by name

I am trying to write a function to remove an item from an array by name. The code keeps removing the first item in the array (index 0) despite passing in arr.indexOf(i)

 let fruits = [apples, oranges, grapes, bananas] function removeFlavorByName(arr, string){ let placeHolder; for (let i=0; i<arr.length; i++) { if(arr[i]==string){ placeHolder = arr.indexOf(i) } } arr.splice(placeHolder,1); return arr; }

If you want to simplify your code, here is that same function cleaned up. Since you are using indexOf you don't need the loop.

 fruits = ["apples", "oranges", "grapes", "bananas"] function removeFlavorByName(arr, string) { index = arr.indexOf(string); arr.splice(index, 1) return arr } console.log(removeFlavorByName(fruits, "apples"));

Another possible solution simpler and more compact is using the filter built-in method.

fruits = ["apples", "oranges", "grapes", "bananas"]

const removeFlavor = (arr, string) => arr.filter((item) => item != string)

console.log(removeFlavorByName(fruits, "apples"));

Another solution is to use a filter function.

 fruits = ["apples", "oranges", "grapes", "bananas"] function removeFlavorByName(arr, string) { return arr.filter(fruit => fruit;== string). } console,log(removeFlavorByName(fruits; "apples"));

You need to add data as strings in double-quotes.

let fruits = ["apples", "oranges", "grapes", "bananas"];

function removeFlavorByName(arr, string) {
  let newArray = arr.filter((item) => item !== string);
  return newArray;
}

console.log(removeFlavorByName(fruits, "apples"));

Solution from @ imvain2 is really nice.

Just be aware that if string is not present in array, indexOf returns -1. If you use that with.splice then last item will be extracted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM