Have you heard of the useful Lodash method called _.pullAt
? It allows you to remove specified elements from an array directly:
_.pullAt(array, [indexes])
This function removes elements from array
based on the provided indexes
and then returns an array containing the removed elements.
You can implement it like this:
var array = ["Apple", "Banana", "Peach", "Pumpkin", "Tomato", "Mango", "Guava"];
_.pullAt(array, [4, 5]);
If you need to remove non-adjacent items, check out this example from the documentation:
var array = ['a', 'b', 'c', 'd'];
var pulled = _.pullAt(array, [1, 3]);
console.log(array);
// => ['a', 'c']
Using this method will simultaneously delete the elements at index 4 and 5 while storing them in a separate array if needed.
An alternative approach using plain JavaScript was pointed out by Nick A., where you can work backwards through the array to remove elements. This technique is effective because removing elements from the end eliminates any issues with changing array lengths. For instance, consider removing the 1st and 3rd elements from the following array:
[1, 3, 7, 9]
If you were to iterate forward, removing element at index 1 (3) would shift all other elements making removal inaccurate. However, by iterating backward and starting with index 3 (9), you avoid disrupting the positions of preceding elements such that the removal process remains intact.