But if it returns -1, then it means there wasn't the element that fit the condition. This will find the first element that satisfies the condition function. We will create a function that takes an array and item as parameters.įirst, to copy the array, we will use the spread operator. We're going to copy the array, find the index, and splice it! const fruits = Ĭonst index = newArray.findIndex((item) => item = "□") Ĭonsole.log(removeItem(fruits, "□")) // output: Here, we will be using the arrow function syntax in ES6. Let's look back at the fruits array again. But what if we don't want to mutate the original array? Something to be extra careful about is when using splice, the original array is mutated, meaning you are changing the original array. Notice how the output of the splice function returns the unicorn in an array, whereas fruits array has changed to a unicorn-free fruit salad. const fruits = Ĭonsole.log(fruits.splice(2, 1)) // outputs: Ĭonsole.log(fruits) // output: The second parameter determines how many items you want to delete, which will be 1. To remove an item using splice, the first parameter is the index of the item we want to remove. Splice mutates the original codeīelow is our array filled with fruits and a unicorn. The return value of the splice method is a new array containing the deleted elements. Splice changes the contents of the array by removing, replacing, or adding new elements. Watch the tutorial here or click the video below to watch it! Method 1: Splice Methodįirst off, what does the splice method do? In this tutorial, we are going to look at how to remove a specific item from an array using JavaScript's native array methods: splice and filter. How would you go about using JavaScript's native array methods to remove that product ID from your shopping cart array? Have you ever been stuck trying to remove a specific item from an array? Imagine this: you are working on a shopping cart delete feature where you need to delete an item that the user doesn't want anymore.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |