What is the best way to delete multiple elements from an array using their index values?

When working with an array, the Array.splice method can be used to remove single values. However, if multiple elements need to be removed from an array, such as element 2, 4, and 8 from an array containing 10 elements, using Array.splice(index,1) in a for loop is not ideal due to the changing index of each element after each splice operation.

To address this issue, how can specific array items be removed and then have the array rearranged 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"]

Answer №1

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.

Answer №2

To reverse loop through an array, you can use the following code:

const fruits = ["Apple", "Banana", "Peach", "Pumpkin", "Tomato", "Mango", "Guava"];
const indexesToRemove = [4, 5];  

for (let i = indexesToRemove.length - 1; i >= 0; i--) {
    fruits.splice(indexesToRemove[i], 1);
}

Check out this JSFIDDLE DEMO for a live example.

Answer №3

To efficiently remove elements from an array without encountering index problems, it's best to proceed in a backward manner rather than reversing the array. Reversing the array can lead to issues with decrementing indices of unchecked elements upon removal.

A useful method for achieving this is `reduceRight`, which functions similarly to `Reduce` but iterates over the array in a right-to-left fashion.

Below is an example illustrating how this concept can be implemented:

var array = ["Apple", "Banana", "Peach", "Pumpkin", "Tomato", "Mango", "Guava"];

let indexToRemove = [4, 5]; //Elements "Tomato" & "Mango" to be removed

array.reduceRight((_, elem, index) => {
    if (indexToRemove.includes(index)) { //Condition for removal
        array.splice(index, 1);
    }
});

console.log(array); //Output: ['Apple', 'Banana', 'Peach', 'Pumpkin', 'Guava']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identifying instances where the AJAX success function exceeds a 5-second duration and automatically redirecting

Greetings! I have created a script that allows for seamless page transitions using Ajax without reloading the page. While the script functions perfectly, I am seeking to implement a feature that redirects to the requested page if the Ajax request takes lo ...

Tips for submitting an AJAX form in grails without relying on a traditional submit button

I am utilizing a g:formRemote tag to submit a form via ajax. <g:formRemote name="listAll" update="menuItemAJAX" url="[controller: 'superWaiter', action:'menuItem']" onSuccess="additionalContent()"> <a h ...

Unable to access an element using jquery

This is an example of an HTML file: <div id ="main"> </div> Here is the JavaScript code: //creating a new div element var divElem = $('<div class="divText"></div>'); //creating an input element inside the div var i ...

Unable to employ regular array methods

What is the reason behind the inability to use the typical array functions in C# such as: string[] k = {"Hello" , "There"}; k.RemoveAt(index); //Not possible When I rely on code completion, I see suggestions like All<>, Any<>, Cast<> or ...

The error message "app.use() function requires middleware function" appears when the app

Currently, I am in the process of learning node.js with express template engine by following a Udemy course called "Learn Node.js by Building 10 Projects". During one of the lectures, when the professor ran npm start localhost:3000, it worked fine for him, ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

Troubleshooting JavaScript directly on the client side

As a JavaScript beginner hoping to transform into a JavaScript expert, debugging is an essential skill I must master. Currently, I am utilizing Chrome debugger tools to tackle a complex array of spaghetti JavaScript code that resembles a cryptic puzzle wai ...

Looking for regex to extract dynamic category items in node.js

Working on node.js with regex, I have accomplished the following tasks: Category 1.2 Category 1.3 and 1.4 Category 1.3 to 1.4 CATEGORY 1.3 The current regex is ((cat|Cat|CAT)(?:s\.|s|S|egory|EGORY|\.)?)(&#xA0;|\s)?((\w+)?([. ...

Issue with PHP retrieving initial value of post data

Hi there, I am facing an issue with my PHP code where the first value of the input field is not being displayed. However, when I check the console.log, it shows correctly. Here is my console.log output: https://i.sstatic.net/eZvg6.png PHP Output: https ...

Utilizing Javascript to maintain an ongoing sum within a <span> tag

I'm working on a code snippet to create a running total feature. Essentially, every time a user clicks a button to add the subtotal to the total, I want it to keep accumulating in the running total. Currently, the setup involves a dropdown menu with t ...

Quickly switch between pages as they load

In Chrome, I'm experiencing a white flash between page loads that is causing transitions to appear choppy. I've taken various steps to optimize the site, such as using image sprites, reducing image sizes, minifying CSS, ensuring correct CSS loadi ...

Flyer: Move to Web Mercator coordinates (EPSG 3857) using panTo

I am currently using a standard leaflet map with a tile layer. In Leaflet, the only way to use the panTo method is by utilizing LatLng, for example, map.panTo(new L.LatLng(40.17, -98.12)); However, I am wondering how I can use the panTo method if my coor ...

Retrieve the associative array from the user input by utilizing jQuery

How can I create an associative array from a form containing multiple text inputs using jQuery (or directly in JS)? Here's an example of the form: <form> <input type="text" name="name[13]" value="test 1" /> <input type="text" name="nam ...

The WebSocket connection in the browser, when accessed through a remote server, typically shows a CLOSED state in the readyState property during the on

Local server operations are running smoothly. However, when testing on a remote server with Nginx, the issue arises where the readyState inside the event handler onopen is consistently showing as CLOSED. Nginx configuration: server { server_name doma ...

Vuetify's v-text-field not properly aligning text to the center

The alignment of the text in v-text-field is causing issues for me, as I am unable to center it. Despite attempting various solutions, I have not been successful. 1. <v-text-field type="number" class="mr-2 text-center"></v-te ...

What is the best way to send a JSON Object containing option parameters in order to open a new window?

Have you noticed the interesting parameter list for the window.open() object? Is there a possibility to use window.open({options..}); instead? What are your thoughts on this matter? ...

What is the method for retrieving authorization response headers in a jQuery AJAX success callback?

While working on setting up encrypted username and password authorization on the front end, I encountered an issue where I am receiving a bearer authorization response header from the server. Interestingly, in Safari, I am able to retrieve this response he ...

Utilizing JavaScript to present JSON data in HTML tables across various sections of a website

Utilizing JScript to retrieve data from a JSON API URL, I have incorporated the data in the JSON file displayed below - containing information on 8 horse races with details like Horse number, Horse name, and their odds. My goal is to create a Jscript code ...

What could be causing the CSS transforms to not show up on the page?

Can't seem to get my navigation panel to slide in when the nav button in the main menu is clicked. I've done this before without issues, so not sure what's up. Any help? Custom HTML Code <!-- Header --> <div class="header"> & ...

I am unable to log in using bcryptjs, but I have successfully been able to register a

Hey there! So I'm diving into Nodejs and I've managed to create a simple login/register API. For password encryption, I'm using bcryptjs. Testing it out on postman, I can successfully register a new user. However, when attempting to login wi ...