What is the most efficient way to loop through these parameters in order to refine an array?

Hello, I need some help with my code. It currently filters an input array to remove any values that match specific arguments. However, I am struggling to iterate through all the arguments effectively. Here is the code that is currently working:

function destroyer(arr) {
  var arg2 = arguments[1];
  var arg3 = arguments[2];
  var arg4 = arguments[3];
  var result = arr.filter(function(arg) {
    if (arg != arg2 && arg != arg3 && arg != arg4) {
      return (arg);
    }
  });
  return result;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

I attempted to iterate through all arguments using a for loop, but it's not working as expected. I'm having difficulty understanding what exactly is being passed through the callback function in the arr.filter method. Here is the code snippet:

function destroyer(arr) {
  var result = arr.filter(function(arg) {
    for (var i = 1; i < arguments.length; i++) {
      if (arg != arguments[i]) {
        return (arg);
      }
    }
  });
  return result;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Am I close to the correct approach or completely off track with my code? Any guidance is appreciated.

Answer №1

The arguments variable is established during each function call, including when your .filter() callback is executed. Therefore, the arguments in that callback may not be what you initially assume.

To achieve your desired outcome, you can utilize the .indexOf method and will have to duplicate the arguments into a separate array:

function destroyer(arr) {
  var badValues = [];
  for (var i = 1; i < arguments.length; ++i)
    badValues = arguments[i];
  return arr.filter(function(value) {
    return badValues.indexOf(value) < 0;
  });
}

Many individuals prefer using .slice() to replicate the entire or portions of the arguments object:

  var badValues = [].slice.call(arguments, 1);

You may opt for this method due to its conciseness, but passing the arguments object outside of a function can hinder optimization efforts significantly.

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

Preventing JSON data from being altered in AngularJS by creating a duplicate copy

It seems like there might be an issue with my implementation of AngularJS. I am trying to create a copy of a JSON object on page load, generate a form using the original data, and then compare the two JSON objects when the submit button is pressed to deter ...

What is the best way to display only a specific container from a page within an IFRAME?

Taking the example into consideration: Imagine a scenario where you have a webpage containing numerous DIVs. Now, the goal is to render a single DIV and its child DIVs within an IFrame. Upon rendering the following code, you'll notice a black box ag ...

Displaying JSON data within a div section using Ajax and jQuery is not possible

I have generated a JSON in a specific format from an external PHP file: [ { "title": "Welcome!", "description": "The world has changed dramatically..", "image": "img/strawberry-wallpaper.jpg" } ] I am trying to use this data to populate a par ...

Activating the Mobile Menu Function when the Window is Resized

I've developed a JavaScript function that triggers on window resize. When switching between landscape and portrait orientation on mobile devices or tablets, the window dimensions change. This functionality is also useful for browser testing on desktop ...

Jquery Deferred failing to activate done or when functions

I'm currently working with 2 ajax calls that I'm connecting using $.when in order to execute certain tasks once they are completed. Below is the code snippet: function ajaxCall(url, targetDiv) { dfd = new $.Deferred(); $.ajax({ ...

Unable to generate a JSON string from the JavaScript object

I need help converting the object I receive from the server into a JSON file for use in a d3.js chart: data = { "dog ":"5", "cat ":"4", "fish ":"12", } The desired output is: { "name" : "animal", "children" : [ {"name":"dog" ...

Why do object == this, but object.member != this.member in the realm of Javascript?

I currently have an object labeled o along with a reference to it. Inside the scope of object o, I define a member named m. Within object o, I execute: o.m = "blah" When I try to access m outside of object o: console.log(o.m) The output is not "blah" ...

The Wikipedia API is unable to be loaded using the XMLHttpRequest

I have encountered this error before on this platform, and although I managed to fix it, I am seeking a more in-depth explanation of the solution. For a project where I am learning, I decided to create a Wikipedia Viewer application. The first step was to ...

Pressing element against another element

I have a somewhat unconventional request - I want to trigger a click event with an HTML element while hovering over another element. Let's imagine we have a .cursor element hovering over an anchor text. In this scenario, clicking on the .cursor shoul ...

Guide to presenting JSON data with ajax

I am trying to dynamically display data based on the selected value from a drop-down list using Ajax's GET method. The idea is to modify the URL by appending the selected item in order to retrieve relevant data from the server: Here is an example of ...

Display validation in HTML5 only when the form is submitted

Here is the code snippet I am referring to: <input required pattern="[0-9]{5,10}" oninput="setCustomValidity('')" oninvalid="setCustomValidity('Type something')" /> I'm looking for a way to remove o ...

Looking to transition from Node.js version v4.4.5 to v6.11.0 on your Windows system?

npm cache clean npm update -g I attempted upgrading using the provided commands, but unfortunately, the update did not go through as expected. Seeking advice for a successful update process. (Currently on Node.js 4.4.5 and aiming to upgrade to Node.js 6. ...

Incorporating a swisstopo map from an external source into an Angular

I am looking to integrate a swisstopo map into my angular 8 app. As I am new to angular, I am unsure how to include this example in my component: I have tried adding the script link to my index.html file and it loads successfully. However, I am confused a ...

The Angular-ui typeahead feature is delivering accurate results when the backspace key is pressed

I've been using Angular-UI typeahead and it's been working fine, but I've noticed a strange behavior when I hit the backspace key - it gives the correct results. For example, if I type sector 4 The result is Sector 1 Sector 2 ...

What are some ways to lazily load directives in AngularJS?

Currently, I am exploring the capabilities of angularjs and aiming to dynamically load directives only when they are required instead of loading all of them initially on the page. My focus is on creating custom directives for the plugins that I use frequen ...

Twice the clicking actions triggered by the event

Whenever I try to trigger a function by clicking on the label text, the click event seems to be firing twice. HTML <label class="label_one"> Label One <input type="checkbox"/> </label> However, if I modify the HTML code as f ...

What sets apart gzip from x-gzip content? And how can I decompress x-gzip specifically? zlib appears to be struggling

One of my npm libraries, named "by-request", has the ability to auto-decompress web content. A snippet of code from this library that handles auto-decompression is shown below: if (!options.dontDecompress || !binary) { if (contentEncoding ...

Saving the index.html file to disk when the button is clicked

Is there a way to export the current HTML page to a file? I have attempted to achieve this using the following code, but it only works when the page is loaded and not with a button click. <?php // Start buffering // ob_start(); ?> <?php file_pu ...

Exploring the capabilities of the Javascript Fetch API by making requests for binary Float32Array data with multiple

I need to fetch multiple 32-bit float values from different parts of a large binary file using range requests. This requires specifying multiple ranges in the request. fetch("http://example.com/largeBinaryFile.bin", { headers: { ' ...

Unable to submit form with Jquery

Having some trouble with my form submission using Jquery. The submit part of my code seems to be malfunctioning, and I can't pinpoint the issue. <?php if(!isset($_SESSION["useridentity"])){ die(header("Location:index.php")); } ...