What is the most efficient way to remove multiple items from an array based on their value?

My goal is to create a function called removeAll() that will eliminate all elements of an array with a specific value, rather than based on index.

The challenge arises when any modifications are made to the loop, causing the indexes to shift (which makes achieving the desired outcome difficult). Restarting the loop every time changes are made is not efficient, especially with large arrays.

To address this issue, I have created my own version of the arr.indexOf function for older IE browsers. Here is the code:

function arrFind(val, arr) {
    for (var i = 0, len = arr.length, rtn = -1; i < len; i++) {
        if (arr[i] === val) {
            return i;
        }
    }
    return -1;
}

Removing elements can be done easily like this:

var myarray = [0, 1, 2, 3, 4];
var tofind = 2;

var stored_index = arrFind(tofind, myarray);
if (stored_index != -1) {
    myarray.splice(stored_index, 1);
}

alert(myarray.join(",")); //0,1,3,4

However, as mentioned earlier, complications arise when attempting this within a loop.

Do you have any suggestions for effectively removing array items while iterating through it?

Answer №1

To reverse the loop order, or create a new array excluding specific items.

Answer №2

Each fresh browser comes equipped with an Array filter function:

var myarray=[0,1,2,3,4];
var removal=2;
var newarray=myarray.filter(function(itm){return itm!==removal});

Answer №3

Give this a try. Simply identify the indexes of the numbers you wish to eliminate. I have included some extra elements in your original array.

var myarray = [0, 1, 2, 3, 2, 2, 2, 5, 6];
var indicesToRemove = new Array();

for(i=0;i<myarray.length;i++){
    if(myarray[i]===2){ //suppose you want to remove all instances of 2 
        indicesToRemove.push(i); //save the indexes in a separate array
    }
}

for (var j = indicesToRemove.length -1; j >= 0; j--){
    myarray.splice(indicesToRemove[j],1);
}

alert(JSON.stringify(myarray)); //myarray will now be [0,1,3,5,6]

Answer №4

Here's a simple function I created that removes specific values from an array, but I'm interested in enhancing it to handle any number of values for removal. As a novice programmer, I'm eager to learn and improve.

function filterArray(arr, val1, val2) {
    var filtered = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] !== val1 && arr[i] !== val2) {
            filtered.push(arr[i]);
        }
    }
    return filtered;

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

Scope Error: Variable 'Undefined' is Not Defined Outside Function in Angular 2

In one of my methods, I am subscribing to an observable and later need to unsubscribe from it in another method. The subCounter() method is triggered from an initialization function and works correctly. subCounter() { this.fml = this.playerService.coun ...

Looping through a dynamic array in Vue.js

I am working with two arrays: days:[0,1,2,3,4,5,6] and wdays:[2,3,6] My goal is to iterate through both arrays and display the output as follows: 0 : not present 1 : not present 2 : present 3 : present 4 : not present etc... The implementation should be ...

Viewing information from the database without the need to refresh the page

HTML <textarea>Enter your question here</textarea><button class="askButton">SUBMIT</button> Upon clicking the button, the question is stored in the database using Ajax, jQuery, and Laravel. However, the question only appears after ...

Troubleshooting issue with caching when integrating new data sources with the Apollo configuration in Keystone 5

On the second request to the server, the returned result is always the cached one, even if the initial request changed the entity. In the file dataSources.js, two instances of each dataSource class are imported: legacyUserApi = new LegacyUserApi(); legac ...

Can we load the form using an ajax request and then submit the form using ajax as

So I have a situation where I am loading a form into a page using an ajax call as shown below: $('.ajax_click').on('click', function(event) { event.preventDefault(); /* Act on the event */ var getmsgtoload = $(this).find(&ap ...

Steps for displaying a division on clicking a hyperlink

I am currently working on my main menu layout in HTML, and here is the code snippet: <div id="main-container"> <div id="main-wrapper"> <div id="logo"> <h1 id="title">port ...

Is it feasible to directly load image objects into jQuery colorbox?

Currently, I am working with the "colorbox" jQuery plugin and I have a specific requirement to dynamically load a set of preloaded image objects into colorbox. The challenge lies in the fact that I have three different image sizes - thumbnail, display, an ...

The JavaScript linked list causes the program to come to a halt

I am currently working on developing a simple web page embedded program using JavaScript. One of the tasks I am tackling involves creating a linked list of all active buttons displayed on the screen at any given time. However, I have encountered an issue w ...

Combining two kebab-case CSS classes within a React component

import React from 'react'; import styles from './stylesheet.moudle.css' <div className={styles['first-style']} {styles['second-style']}> some content </div> What is the correct way to include styles[&ap ...

Having trouble navigating the Request and Response handling in Expressjs/Nodejs?

As I continue to delve deeper into this code, confusion seems to cloud my understanding. Here is the provided source: var express = require('express') , http = require('http') , server = express() ; var home = require('./ro ...

The async function in Jasmine is causing issues with expectedAsync functionality

Currently conducting the following examination: it("should receive rejection", async done => { class someTest { async run(){ return this.rejectFunc(); } async rejectFunc(){ return new Promise( ...

A guide on showcasing a MultiPolygon GeoJSON on a Leaflet map

I am attempting to showcase a GeoJSON MultiPolygon object on a Leaflet map. I retrieve it from a PostgreSQL database as JSON and transform it into GeoJSON. I have validated the MultiPolygon object on GeoJSONLint and it checks out: However, I am facing di ...

Triggering a click event within a Bootstrap popover

Clicking the inbox button triggers the inbox_open() function. When this function runs, three buttons appear in the inbox header but there is no onclick event listener attached to them. Make sure to review the code after the // inbox.open comment for critic ...

"Explaining like you're five: How to use a new npm

When working with static, fully custom websites, I often face confusion on how to include packages. For instance: I understand creating the package.json file. I know how to install and --save the package into the package.json file. But what comes next? ...

AngularJS controllers and $scope are essential components in structuring and

As a newcomer to Angular, I've spent some time reading up on scopes and controllers, but I still feel like something isn't quite clicking for me. Let's take a look at this code snippet: var myApp = angular.module("myApp", []); myAp ...

What could be causing my div link to redirect to different content instead of the intended destination?

When creating a div to provide information about a course, including the price and a "Take Class" button that links to the purchase page, I encountered an issue where the link extends beyond the intended area. @import url(https://fonts.googleapis.com/cs ...

Troubleshooting EJS Relative Path Problem when Using "include" in an HTML Document

I'm encountering an issue with my "index.ejs" file... The current content of the ejs file: <!DOCTYPE html> <html lang="en" dir="ltr"> <!-- THIS SECTION IS FOR <head> TAG THAT WILL BE STORED INSIDE "so_ ...

Techniques for capturing Django's output from an Ajax request

I've been trying to utilize Ajax for converting my form data to JSON and sending it to my Django view. However, I'm encountering an issue where after successful processing in the view, I am returning a template response with some context data tha ...

Having trouble troubleshooting the jQuery button

When I click this button, it triggers an ajax call that updates the score_up value. I can't seem to figure out what's wrong. I attempted using Firebug, but it doesn't detect the JavaScript. Any help would be appreciated! Here is the jQuery ...

Utilizing a parent scope variable in a callback function

This question delves more into the concept of JavaScript Closures rather than Firebase. The issue arises in the code snippet below, where the Firebase callback fails to recognize the variable myArr from the outer scope. function show_fb() { var myAr ...