removing a particular item from an array in Javascript

Currently, I am conducting an experiment on removing objects from an array. Please note that this code is not formal as it is intended for testing purposes.

<script type="text/javascript">

// Initialize array and objects
var fruits = new Array();

var obj1 = {
  test1: "test0",
  test2: "test2"
}

fruits.push(obj1);
var obj2 = {
  test1: "test1",
  test2: "test2"
}
fruits.push(obj2);
var obj3 = {
  test1: "test2",
  test2: "test2"
}
fruits.push(obj3);
var obj4 = {
  test1: "test3",
  test2: "test2"
}
fruits.push(obj4);
var obj5 = {
  test1: "test4",
  test2: "test2"
}
fruits.push(obj5);

// Display array length
document.write("The array's length is " + fruits.length + "<br>");

// Traverse the array
for(var i = 0; i < fruits.length; i++){

  // Display object content within the array
  document.write(fruits[i].test1 + " ");

  // Delete object in the array if variable test1 is equal to "test2"
  if(fruits[i].test1 == "test2"){
    fruits.splice(i, 1);
    //document.write("array length is " + fruits.length + "<br>");
  }
}
</script>

The code above currently works for removing an object from the array. However, it deletes the object following the one intended for deletion (for example, wanting to remove index 2 results in index 3 being deleted).

Is there anything flawed with the current implementation?

Thanks in advance :)

Answer №1

One should always avoid modifying an array while iterating through it. It's best to store the index of the element you wish to remove in a separate variable and delete it once the loop is complete.

Answer №2

Here is a possible solution:

<script type="text/javascript">

    // create an array and objects
    var vegetables = new Array();

    var y = {
      test1: "carrot",
      test2: "radish"
    }

    vegetables.push(y);
    var y2 = {
      test1: "cucumber",
      test2: "lettuce"
    }
    vegetables.push(y2);
    var y3 = {
      test1: "broccoli",
      test2: "spinach"
    }
    vegetables.push(y3);
    var y4 = {
      test1: "pepper",
      test2: "onion"
    }
    vegetables.push(y4);
    var y5 = {
      test1: "zucchini",
      test2: "celery"
    }
    vegetables.push(y5);

    // display the length of the array
    document.write("The array's length is " + vegetables.length + "<br>");

    // iterate through the array
    for(var i = 0; i < vegetables.length; i++){

      // display the content of each object in the array
      document.write(vegetables[i].test1 + " ");

      // remove the object from the array where 'test1' is equal to "cucumber"
      if(vegetables[i].test1 == "cucumber"){
        vegetables.splice(i-1, 1);
        //document.write("The array's length is " + vegetables.length + "<br>");
      }
    }
</script>

Answer №3

To utilize the ``filter`` function from underscore.js, you can do the following:

_.filter(fruits, function (fruit) {
    return fruit.test1 !== "test2";
});

This method is beneficial because it leverages a speedy, built-in JavaScript function (''filter'') when it's supported by the browser.

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

Can you suggest a method using Lodash to remove specific rows from an array based on the value of a certain field within the array?

Currently, I am utilizing the following function: remove: function (arr, property, num) { for (var i in arr) { if (arr[i][property] == num) arr.splice(i, 1); } }, Although this functi ...

Sending a parameter to a JavaScript function on a separate page

My current setup involves an aspx page featuring a drop down list. Once a selection is made, I am required to transmit the chosen value to a separate javascript function located within another page. This second page is dedicated to showcasing a map using ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

Change the text inside a div when hovering over it using fadeIn and fadeOut effects

I'm attempting to change the content of a div when a user hovers over it. I've set up two divs. The default is the foreground div, and when hovered over, I want to hide the foreground and display the background div. $('.background' ...

Converting an object into a list of lists using Typescript

When making an API call from Angular 5, the response is returned in the following format. { "metadata":{ "lastSyncTime":"2000-11-21T16:07:53", "dataFromDB":true }, "allocationReports":[ ...

Setting up Npm Sequelize Package Installation

Could use some help with setting up Sequelize. Here's the current status: https://i.sstatic.net/MQH1I.jpg ...

Encountering issues while creating a basic digital clock webpage using React

I am trying to create a simple clock in React, but I want all the time data to be stored in a single object instead of separate states for hours, minutes, and seconds. However, I keep running into an error. Can someone please assist me? import React from & ...

Resolving unexpected behavior with res.locals and pug integration

I have a function in my app.js that allows the user-id to be accessible in pug templates. app.use(function (req, res, next) { res.locals.currentUser = req.session.userId; next(); }); When logged in, I can access the id. However, when not logged in, t ...

Conclude the execution of promises after a for loop

I'm looking to enhance my code by ensuring that it waits for the asynchronous query called prom to finish before resetting the array and restarting the first for loop. This way, the array will be cleared before the loop begins again. items = []; var ...

Encountering a maximum call stack size error is a common issue when implementing d3.layout.partition in Angular

I recently developed an AngularJS directive to generate a D3 sunburst chart, but I'm encountering issues. I'm receiving a maximum call stack error in Chrome and a too much recursion error in Firefox. After some investigation, I found that the pro ...

Having trouble with jQuery animate function?

I have been struggling to get my animate function to work, despite looking at multiple similar posts and making modifications to my code. My goal is to make an image of a plane move from left to right across the screen and stop halfway. Here is the code I ...

Utilized controller's isolated scope inheritance to enhance the reusability of the directive

How can I create an isolated scope in a controller to make a reusable directive? Take a look at my code snippet below: (function (app) { // Declare the Template var template = function (element, attrs) { var htmltext = '& ...

Refresh the DOM window to load the updated PHP element

I have a dilemma with two separate playlists in a PHP file, each corresponding to a button labeled playlist1 and playlist2. <div class="player"> <?php include ('playlist1.php');?> <?php include ('playlist2.php'); ...

instructions for executing this javascript within the <p> tag

This is the code I have written : <p onload=javascript:alert('sss')>www</p> Unfortunately, the code does not alert 'sss', Can someone please tell me what's wrong with my code? Thank you ...

Having trouble aligning a div in the middle of a slick-slider item using flex styling

I've created a slick slider component in Vue, and I'm facing an issue with centering a circular div inside each of the slider items. Despite trying to align and justify center along with adding margin:auto for horizontal centering, I can't s ...

Steps to convert the value from False to True with just a simple press of a

I'm currently learning React.js and I wanted to create this specific application. My goal is to figure out how to toggle between False and True using action buttons. Whether you can provide an explanation or show me an example, it would be greatly app ...

Why does the first value always get returned in my select no matter which option I select?

It's getting late and I'm struggling with what seems like a simple fix. I've looked through several posts on StackOverflow but I still can't seem to get this working. My issue is with a select element that has 7 options, each with a nu ...

Modifying an HTML list item to become 'active' in a navigation bar

One way I've been implementing my navbar on each page is by using the following code at the bottom of the page within script tags: $("#navbar-partial").load("navbar.html). The code for the navbar list looks like this: <ul id="main-nav" class="nav ...

Does the round function always produce the most accurate floating point approximation?

Will the result of using round(3.12143345454353,2) always be equivalent to simply using the literal value 3.12? The floating point approximation would suggest so (3.12000000000000010658141036401502788066864013671875). In simpler terms, can we rely on the ...

I am experimenting with an express middleware that can either return next() or next("route")

After developing a middleware function that returns next() if a route's parameters are defined by queryItems, I came across a useful tool called node-mocks-http. However, it does not fake the next object. This led me to explore how this can be achieve ...