Delete a specified element from an array

I am currently in the process of re-learning JavaScript, and unfortunately, I'm facing some difficulties.

Here's the challenge at hand:

In the destroyer function, you will receive an initial array as the first argument. Following that, one or more arguments will be provided. The goal is to remove all elements from the initial array that have the same value as these arguments.

I need help understanding why the code snippet below is not removing the necessary elements for the second test case.

function destroyer(arr) {
  console.log(arguments);

  for (var array_i = 0; array_i < arr.length; array_i++){
    for (var arg_i = 1; arg_i < arguments.length; arg_i++){
      console.log("indexes", array_i, arg_i);
      if (arr[array_i] === arguments[arg_i]){
        console.log(arr[array_i], arguments[arg_i], "destroyed");
        arr.splice(array_i, 1);
        console.log(arr, arguments);
        array_i = 0;
        arg_i = 1;
      }
    }
  }
  return arr;
}

The code works as expected in this scenario:

destroyer([3, 5, 1, 2, 2], 2, 3, 5);

However, it fails to produce the desired outcome in this case:

destroyer([2, 3, 2, 3], 2, 3);

Answer №1

Instead of trying to compensate for the elements removed along the way by resetting your indices, a more effective approach is to delete from the end of the array. This method is simpler and does not require any resets.

function destroyer(arr) {

  for (var array_i = arr.length - 1; array_i >= 0; array_i--){
    for (var arg_i = 1; arg_i < arguments.length; arg_i++){
      if (arr[array_i] === arguments[arg_i]){
        arr.splice(array_i, 1);
        break;
      }
    }
  }
  return arr;
}

console.log( destroyer([2, 3, 4, 2, 3], 2, 3)  );   // [4]
console.log( destroyer([2, 3, 2, 3], 2, 3)  );      // []

Answer №2

The issue lies in the fact that you are altering the array while iterating through it.

One way to solve this problem is by using the filter function instead:

function removeElements(arr) {
  var args = [].slice.call(arguments);
  return arr.filter(function(item) {
    return args.indexOf(item) == -1;
  });
}
document.getElementById('output').innerHTML = 
  JSON.stringify(removeElements([2,3,2,3], 2, 3)) + "\n" +
  
  JSON.stringify(removeElements([1,2,3,4,2,3], 2, 3))
<pre id="output"></pre>

Answer №3

An approach to eliminating unwanted elements from an array without altering the original array's content.

function remover(inputArray) {
  var excluded = Array.prototype.slice.call(arguments, 1);
  excluded.forEach(function(item) {
    var index = inputArray.indexOf(item);
    while (index > -1) {
      inputArray.splice(index, 1);
      index = inputArray.indexOf(item);
    }
  });
  return inputArray;
}

var list1 = [2, 3, 2, 3];
remover(list1, 2, 3);
document.getElementById('output1').textContent = JSON.stringify(list1);
console.log(list1);

var list2 = [3, 5, 1, 2, 2];
remover(list2, 2, 3, 5);
document.getElementById('output2').textContent = JSON.stringify(list2);
console.log(list2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.4.1/es5-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<pre id="output1"></pre>
<pre id="output2"></pre>

Answer №4

The issue at hand is relying on the length to iterate through an array while simultaneously reorganizing its elements. This can lead to problems where, after removing certain elements, those same elements end up back at the beginning of the array, causing the loop counter to skip over necessary positions. To avoid this issue, it's better to loop through each argument only once and search for it in the array.

for(var i = 1; i < arguments.length; i++)
{
    var index = arr.indexOf(arguments[i]);
    while(index > -1)
    {
        arr.splice(index, 1);
        index = arr.indexOf(arguments[i]);
    }
}

By following this approach, you will achieve the desired outcome without complications.

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 is the best way to arrange the elements of an array based on a specified value?

Is there a way to develop a function that can organize an array of data based on the value of a specified field? Suppose the field consists of three numbers: 1, 2, 3. The idea is that upon providing a certain value to the function, it will rearrange the ta ...

I am interested in extracting the "Index array" from a multi-dimensional array

Creating a multi-dimensional array occurs by following these steps: List<int> indexList = GetFromSomewher() Results = Array.CreateInstance(typeof(System.Double),indexList.ToArray() ); foreach (DataRow row in table.Rows) { Li ...

Choose images at random from an array within a React Native application

I've been working on a feature that involves randomly selecting an image from an array of images. However, I keep running into the issue of getting an "invalid props source supplied to image" error. My goal is to display a different random image each ...

Introducing the new default in Google Chrome: Now accessing window.opener for target="_blank" links after rel="noopener" is the standard feature

Exploring a new attribute called rel="noopener", I discovered that it keeps opened windows unaware of their opener. After some experimentation, I consistently found window.opener === null, only to realize that this is now the default behavior in ...

Deactivating the submit button after a single click without compromising the form's functionality

In the past, I have posed this question without receiving a satisfactory solution. On my quiz website, I have four radio buttons for answer options. Upon clicking the submit button, a PHP script determines if the answer is accurate. My goal is to disable t ...

Adjust the value before moving to the next tab, or if you choose to leave the

Looking for help to display a popup message when a user edits any value? Check out this resource that I found. It currently only triggers when moving to another page, but I need it to work within an Ajax tab system as well. Here is the code I have tried: ...

Transforming javascript's array.map into php's array_map function

The following code snippet is written in JavaScript and consists of a hashmap array with keys and values. I have created a function using map that returns the values of the entered keys. var rule = { "c": "d", "a": "o", "t": "g", "h": "a", "e": "n", "n": ...

Unable to Retrieve Modified Content with $().text();

In the process of developing an app, I am encountering a challenge where I need to transfer user input to another element after processing it. However, I am facing an issue with accessing the updated value of the <textarea> using .text(), as it only ...

Promise rejection not handled: Trying to modify headers after they have already been sent to the client

I can't seem to figure out why these errors keep popping up. I've tried looking for solutions online but haven't had any luck. Here is the node function I'm using for an API call: exports.GetEmployeeConfirmationList = function (req, res ...

Transforming a numerical function into an HTML span tag: A quick guide

Looking for assistance with updating the last line. The goal is to display the current month, obtained from the getMonthText variable, within the <h1><span id="month_year">&nbsp;</span></h1> Starting code. The issue arises to ...

Updating votes on the client side in WebForms can be achieved by following these steps

I am currently working on implementing a voting system similar to Stack Overflow's. Each item has a vote button next to it, and I have it functioning server side causing a delay in reloading the data. Here is the current flow: Clicking the vote butt ...

Error encountered in jQuery validation script due to incorrect data type

Looking to experiment with the jQuery validate plugin in an MVC application by trying a simple example. Here is a JS module with a method: ValidateRestriction: function (element) { var inputs = $('form').validator(); inputs.data("validat ...

JavaScript nested function that returns the ID of the first div element only upon being clicked

I am facing an issue with a function that returns the id of the first div in a post when an ajax call is made. The problem is that it repeats the same id for all subsequent elements or div tags. However, when the function is used on click with specified ...

What causes errors in my AJAX request based on the particular file extension?

Utilizing JavaScript and jQuery, I have a function that loads data using $.get(url, function(response){ /* ... */});. The data is retrieved from a text file and handled within the response function of the JavaScript. Recently, I encountered an issue on my ...

Exploring AngularJS with Filtering for Advanced Search Results

Currently, I have a search box that successfully searches values in a table using my code. <tr ng-repeat="b in bugs | filter:searchText"> Now, I want to take it one step further by allowing users to search specific columns if they include a colon i ...

Unusual occurrences regarding scope in the world of JavaScript and d3.js

Currently, I am working on a project using a mix of react.js and d3.js. While coding, I encountered a strange behavior that I can't quite figure out. componentWillMount() { this.setState({ dummyData: [{ price: 13, ...

Tips for integrating jwt token into axios request

I am facing an issue with my backend endpoint. I can successfully retrieve a list of customers using jwt token on Postman, but when I try to fetch the list from a React app using axios get request, it fails. After reading through this question, I implemen ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...

Python - Assigning Values in a Nested Array

Check out the function below: def adjust_values(self,index1, index2, val): print('Adjusting values with index1 : ' + str(index1) + ' , index2 : ' + str(index2) + ' and value : ' + str(val)) print(self.values) self ...

Angularjs - Navigating the Depths of OrderBy: Effective Strategies for Handling Complex Sorting Structures

I have a collection of Incidents (displayed as an array below) that I need to sort meticulously by State, Priority, and Start_date. Specifically, I want them ordered in the sequence of Initial > Ongoing > InReview > Resolved for State, then Priori ...