Removing a Specific Element by Value
- To remove an element from an array based on the value in JavaScript is to find index number of that value in an array using indexOf() function and then delete particular index value using the splice() function.
Example 1:
[ad type=”banner”]- We have initialized an array named arr with few static values.
- Now we can use indexOf() function to find the index number of given value in array.
- If given value found in array , it will return index number, else it will remove values less than 0.
- First check if return index number is >=0, then only delete the value from that index from array using splice() function.
Removing One Element Using splice()
- The splice() method is a useful way of removing, replacing, and/or adding elements in an array.
- similarly to works with splice() functions in other languages.
- We are take an array and selectively remove portions of it (aka “splice”).
- The inputs to the splice() function are the index point to start at and the number of elements to remove.
- Also, remember that arrays are zero-indexed in JavaScript.
To remove one element from a specific index in an array:
[ad type=”banner”]- The splice() call will return any removed elements, so we know what was actually removed.
Removing a Range of Elements Using splice()
- To remove several consecutive elements from an array:
Removing One Element Using pop()
- The array methods of push() and pop() work on the the end of an array.
- In terms of push() and pop() come from the idea of a stack in memory from microprocessors.
- This implements the idea of a Last-In-First-Out data structure (LIFO).
- The push() method will ADD an element to the array and the pop() method will remove one.
Here the example is remove the last element of an array:
Removing One Element Using shift()
- The array methods shift() and unshift() work on the beginning of an array instead of the end of an array, as is the case with push() and pop().
- The shift() command will remove the first element of the array and the unshift() command will add an element to the beginning of the array.
The below example is remove the first element of an array:
[ad type=”banner”]Removing Multiple Specific Elements
- Let’s add an extra “wikitechy”element to our array, and then remove all occurrences of “wikitechy
Note:
- To use the filter() method for this operation, but that would have created a new array, as filter() does not mutate the array.
- If you need to do a lot of filtering, using the filter() method might clean up your code quite a bit
wow