Using a Array.splice is fine as long as it's a single value.
Suppose I have an array with 10 elements and I want to remove element 2,4 and 8, using Array.splice(index,1) in a for loop is a bad idea because the index of each element changes after each splice operation.
How can I remove specific array items and then re-arrange the array accordingly
var array = ["Apple", "Banana", "Peach", "Pumpkin", "Tomato", "Mango", "Guava"];
remove(array, 4,5); //Is there a lodash function for this?
//desired result --> ["Apple", "Banana", "Peach", "Guava"]
There's a Lodash method _.pullAt that pulls elements out of the array (in place) that are specified in an array:
_.pullAt(array, [indexes])Removes elements from
arraycorresponding toindexesand returns an array of removed elements.
Thus, apply it like this:
var array = ["Apple", "Banana", "Peach", "Pumpkin", "Tomato", "Mango", "Guava"];
_.pullAt(array, [4, 5]);
And if you want to pull out non-adjacent items (from the documentation):
var array = ['a', 'b', 'c', 'd']; var pulled = _.pullAt(array, [1, 3]); console.log(array); // => ['a', 'c']
This will remove the elements at index 4 and 5 in place, and also return the removed element (if you need it).
You could, of course with vanilla JavaScript, look backwards as Nick A. mentioned and remove items from the back. The reason this works is because removing from the back will not make a changing length an issue. Consider this example where I want to remove the 1st and 3rd elements:
[1, 3, 7, 9]
If I were to loop 'forwards', I would remove element at index 1 (3), but the length would change to 3 and there would be no element at index 3! If I were to loop backwards though, I would remove the element at index 3 first (9). Then the length would be 3, but that doesn't affect any elements before it, the element at index 1 is still at index 1 thus removing from the back works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With