Remove an element from an array in JavaScript when a condition is met in an if/then statement

I am currently working on a function that loops through elements in an array and removes values outside of a specific range. However, I have encountered an issue where using the pop method always removes the last element in the array rather than the intended value within the if/then statement.

Below is the code snippet I am using. I have also attempted to use the splice method without success. Any suggestions on how to fix this problem would be greatly appreciated!

    var h = [
    ["29","Verbena St", "500", "2", "2,702"],
    ["36", "Quitman St", "400", "2", "1,700"],
    ["32", "Alan Dr", "500", "2", "2,408"],
    ["34", "Newton St", "300", "2", "1,954"],
    ["30", "Soth Pl", "400", "2", "1,509"]
    ];

    var hs = [
     ["Verbena St"],
    ["Quitman St"],
        ["Alan Dr"],
     ["Newton St"],
     ["Soth Pl"]
    ];


function Location (){

    for (var r = 0; r <= h.length; r++){
        var p = h[r][0];
    var address = h[r][1]; // Get address
        if (p >= 21 && p <= 33 && address == hs[r]){
            console.log(address);
        }
        else {
            console.log(address + " - OVER 33");
            h.pop(address);
            console.log(address + " - REMOVED");
        }
   }
};

Location();

Answer №1

One efficient way to avoid removing elements from an array while iterating through it is by utilizing the filter() method. Here's an example:

var h = [
  ["29","Verbena St", "500", "2", "2,702"],
  ["36", "Quitman St", "400", "2", "1,700"],
  ["32", "Alan Dr", "500", "2", "2,408"],
  ["34", "Newton St", "300", "2", "1,954"],
  ["30", "Soth Pl", "400", "2", "1,509"]
];

var hs = [
  ["Verbena St"],
  ["Quitman St"],
  ["Alan Dr"],
  ["Newton St"],
  ["Soth Pl"]
];

function Location (){
  h = h.filter(function(r, i){
    var p=r[0];
    var address = r[1]; 
    return p >= 21 && p <= 33 && address == hs[i];
  });
};

Location();
console.log(h);

If you need to display messages instead, you can create another array and selectively add elements to it using a forEach loop:

var h = [
  ["29","Verbena St", "500", "2", "2,702"],
  ["36", "Quitman St", "400", "2", "1,700"],
  ["32", "Alan Dr", "500", "2", "2,408"],
  ["34", "Newton St", "300", "2", "1,954"],
  ["30", "Soth Pl", "400", "2", "1,509"]
];

var hs = [
  ["Verbena St"],
  ["Quitman St"],
  ["Alan Dr"],
  ["Newton St"],
  ["Soth Pl"]
];

function Location (){
  var g = [];
  h.forEach(function(r, i){
    var p = r[0];
    var address = r[1];
    if (p >= 21 && p <= 33 && address == hs[i]){
    console.log(address);
      g.push(r);
    }
    else{
      console.log(address + " - OVER 33 - REMOVED");
    }
  });
  h = g;
}

Location();
console.log(h);

Answer №2

To efficiently remove elements from an array, consider looping from the end and using splice when necessary. This approach ensures that the smaller index positions are not affected.

function updateLocation() {
    var address, p, r = h.length;
    while (r--) {
        p = h[r][0];
        address = h[r][1]; // Retrieve address
        if (p >= 21 && p <= 33 && address == hs[r]) {
            console.log(address);
        } else {
            console.log(address + " - OVER 33");
            h.splice(r, 1);
            console.log(address + " - REMOVED");
        }
    }
}

var h = [["29", "Verbena St", "500", "2", "2,702"], ["36", "Quitman St", "400", "2", "1,700"], ["32", "Alan Dr", "500", "2", "2,408"], ["34", "Newton St", "300", "2", "1,954"], ["30", "Soth Pl", "400", "2", "1,509"]],
    hs = [["Verbena St"], ["Quitman St"], ["Alan Dr"], ["Newton St"], ["Soth Pl"]];

updateLocation();
console.log(h);

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

What are some strategies for optimizing speed and efficiency when utilizing jQuery hover?

While developing a web application, I have created a grid using multiple div elements that are X by Y in size, determined by user input. My goal is to change the background color of surrounding divs within a certain distance when hovering over one particul ...

Determine if an HTML element contains a specific class using JavaScript

Is there a simple method to determine if an HTML element possesses a particular class? For instance: var item = document.getElementById('something'); if (item.classList.contains('car')) Remember, an element can have more than one clas ...

Tips and tricks for activating javax.script in Websphere liberty profile on Bluemix

I am looking to incorporate JavaScript into one of my Java applications. In order to test this, I executed the following code: javax.script.ScriptEngineManager manager = new ScriptEngineManager(); javax.script.ScriptEngine engine = manager.getEngineByName ...

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

Issue with symbol not functioning on different device

There seems to be a display issue with the ...

Using a PHP associative array to merge tables with identical field names

Currently, I am facing an issue with a particular query where I am trying to retrieve data from an array but struggling to identify the key names: SELECT table_1.*, table_2.* FROM... INNER JOIN... I have looked into similar posts for a solution and fou ...

Having difficulty implementing dynamic contentEditable for inline editing in Angular 2+

Here I am facing an issue. Below is my JSON data: data = [{ 'id':1,'name': 'mr.x', },{ 'id':2,'name': 'mr.y', },{ 'id':3,'name': 'mr.z', },{ & ...

Navigating to the next or previous item in an Angular2 Firebase collection based on the current key

In my photo gallery, I have the key of an item in firebase and would like to enable users to navigate to the next or previous picture by pressing buttons. In a non-Angular2 context, I might use the following code snippet to retrieve the next item: ref.ord ...

Reload entire page for AJAX request if JavaScript is not enabled

Currently utilizing JSF2. I have a button that triggers an action and then updates a section of the page (fairly standard). <h:commandButton value="foo" action="#{myBean.myAction}" > <f:ajax execute="@form" render="#content" /> ...

Jackson is able to deserialize an array of objects into a POJO

So I am working with a JSON file that looks like this: { "results":[ "result":{}, "result":{} ] } My goal is to deserialize this JSON data into a Java object that consists of an array of result objects. public class Fo ...

Using Leaflet to set the view based on a GeoJSON dataset

I am working on incorporating a leaflet.js map with a square shape imported from an external GeoJSON file. I have determined the exact coordinates for the center of the square, and now I need to convert these coordinates in order to pass them correctly t ...

Transferring data-id to a Bootstrap modal without the use of jQuery

I've come across numerous questions similar to this, all suggesting the same solution of using JQuery. However, incorporating JQuery into my Reactjs project just to pass an id to a modal is something I wish to avoid. Below is my code snippet : <! ...

AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them. Currently, it seems like all th ...

"Enhance Your WordPress Website with the Power of jQuery

I have been developing a unique Wordpress plugin that incorporates a grid loading effect using jQuery. The script I have implemented is as follows: <script type="text/javascript"> new GridScrollFx( document.getElementById( 'grid' ), { ...

Issue with array doesn't update when switching positions of elements

I encountered a strange issue while working on my visualizer for sorting algorithms. Everything was going smoothly until I reached the Selection Sort algorithm. The problem lies in the fact that the i value doesn't seem to change during each pass, cau ...

Adding jQuery and other libraries to Typescript for optimal functionality

After spending days researching and struggling, I am reaching out here for clarification on the process of importing a library in Typescript. I used to just add the script tag and everything would work fine. Now that I am working on building a MEAN-Stack ...

What sets apart toBeInTheDocument from getBy* in @testing-library/react?

Can you distinguish between these two methods in react-testing-library? expect(screen.queryByText('<something>')).toBeInTheDocument(); And screen.getByText('<something>'); (The specific getBy* and queryBy* operation are no ...

NodeJS web scraping on a site that uses JavaScript

Currently, I am utilizing the request method to extract data from a particular SoundCloud page. Upon loading, SoundCloud verifies if JavaScript is enabled before displaying the track list. However, during my scraping process, I am only receiving a basic H ...

What are your thoughts on the size of a React component being 500 lines long?

Currently, I am in the process of constructing a Table component that includes filters and requires an extensive amount of logic. Additionally, I have incorporated material UI which tends to add multiple lines of code. Despite these elements, I feel that ...

Synchronously retrieving JSON data from a URL using JavaScript

I'm currently working on extracting the title of a YouTube video using jQuery to parse JSON. The issue I am facing is that it works asynchronously, resulting in the answer being displayed after the page has already loaded. Here's the current resu ...