Filtering Out Elements from an Array with the Filter Method

How can I efficiently remove all elements from an array that match the values of subsequent unknown arguments? Here's my current approach:

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

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

Answer №1

Utilize Array#filter alongside arrow function Array#includes and rest parameters.

Demo

function destroyer(arr, ...remove) {
    return arr.filter(e => !remove.includes(e));
}

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

function destroyer(arr, ...remove) {
    return arr.filter(e => !remove.includes(e));
}

var updatedArr = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
console.log(updatedArr);

Corresponding Code in ES5:

function destroyer(arr) {
    var toRemove = [].slice.call(arguments, 1);
    return arr.filter(function(e) {
        return toRemove.indexOf(e) === -1;
    });
}

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

function destroyer(arr) {
    var toRemove = [].slice.call(arguments, 1);
    return arr.filter(function (e) {
        return toRemove.indexOf(e) === -1;
    });
}

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

Answer №2

Utilize rest parameters to define the additional arguments, apply the Array.prototype.filter() method with an arrow function to filter the arr array, and use Array.prototype.includes() to check if args contains a specific item.

function destroyer(arr, ...args) {
  return arr.filter(x => !args.includes(x));
}

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

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

A code snippet designed to ensure uniform height for all floating div elements

Hello, I am facing an issue with resizing 20 left-floated divs of varying heights on my website. Previously, when my website was designed using pixels, a script worked perfectly for resizing them. However, after switching to a percentage-based design (% d ...

What are the steps to troubleshooting using VS Code and Chrome browser with Webpack?

Can anyone provide guidance on how to debug webpack in VS Code with the Chrome browser? As a beginner in programming, I'm struggling because webpack minifies everything into one line which makes traditional debugging methods ineffective. I haven' ...

Prevent text from wrapping when using jQuery to animate font size

I have a unique way of showcasing content in a preview format by utilizing em units for scaling and adjusting the root font size to increase or decrease. When users click on the preview, the full content is revealed with an animation that scales the font s ...

Axios is repeatedly making GET requests to an incorrect endpoint

I have set up axios to make requests to my express backend hosted on localhost:8081 src/htpp/index.js import axios from 'axios' export default axios.create({ baseURL: 'http://localhost:8081/api/', timeout: 1000, headers: {&apos ...

tips for integrating external javascript in react applications

If you are working on an HTML page, you can include a JavaScript file using the following syntax: <script src="path"></script>. However, when it comes to retrieving variables from an external path in React, things get a bit more complex. For in ...

How can I bind an event for changing innerHTML in Angular 2?

Is there a way to implement something similar to this: <div [innerHTML]="content" (innerHTMLchange)="contentInit()"></div> Currently, I have a variable content that is updated by a service fetching a string from my express server. The content ...

I often find myself yearning for the good old days of prototyping functions when initializing a new

I just created a module in nodejs called Test.js with the following code: function Test() { this.key = 'value'; } Test.prototype.foo = function () { return 'foo'; } module.exports = Test; Then, in B.js file: var Test = require(&a ...

Increase the placeholder's line height and font size for the InputBase component in Material UI

Hello, I am new to material UI and currently using it for my website development. I am trying to customize the placeholder of the inputbase in material ui by increasing their lineHeight and fontSize. However, I am having trouble accessing the placeholder A ...

The 404 Page Not Found error is displayed when an Angular JS Encoded URL

I have successfully developed an AngularJS application. The application functions properly with the URL provided below: http://localhost/AngularDemo/about However, when I try to modify the URL as shown below, it redirects me to a 404 error page: http:/ ...

Transferring Session ID between Express.js and Socket.io while dealing with iframes from distinct origins

My Node application built with Express.js and Socket.io is facing an issue where they are not sharing the same session ID when running under iframe with different origins. When accessed directly or through iframes with the same origin, everything works fin ...

Are queued events in React discarded upon a state change?

As I develop a React form component with simple validation, I encounter an issue where the onBlur event of a field and the onSubmit function of the form are triggered simultaneously. If there is a change in the state during onBlur, the onSubmit function do ...

Tips for transferring form data between pages using ReactJS?

Custom Checkout Implementation This section pertains to the custom checkout implementation utilizing Javascript. The goal is to extract form fields from the CheckoutForm page and utilize them within this checkout.js file for database submission. This pre ...

Retrieve the chosen element from a jstree

How can I retrieve the selected Node from a jstree? This snippet shows the code in the View section: <div id="divtree" > <ul id="tree" > @foreach (var m in Model.presidentList) { <li class="jstree-clicked ...

Is Angular 2+ responsible for loading the entire module or only the exported components within it?

I'm dealing with a situation where I have a large module but only need to export one specific component. I'm wondering if Angular loads the entire module or just the exported components, as I want to optimize performance without compromising the ...

Issue with Vuetifyjs theme variable failing to function properly in version 1.0.0

Check out the step-by-step instructions provided in https://vuetifyjs.com/en/style/theme. I successfully changed the theme using the code below with vuetifyjs version 0.13.0. However, after updating to vuetifyjs 1.0.5, the font still displays correctly bu ...

Loading Animation with jQuery and Minimum Time Delay

Hello there, I am looking for a way to establish a minimum time duration for an onload function to ensure that a div is displayed for at least 2 seconds. Similar to setting a min-width or min-height, I want the div to be shown for a minimum of 2 seconds e ...

Combining a 3D array with a 4D array

I am striving to create a 4D array where each "value" k in the fourth dimension corresponds to the kth 3D tensor. Despite trying various approaches, I keep encountering the error message saying "all the input arrays must have the same number of dimensions" ...

Terminate child process with specified user ID using the Forever-monitor

Whenever I need to create new child node processes, I use the following code: var forever = require('forever-monitor'); function startNodeProcess(envVariables, jsFileName, uid) { var child = new (forever.Monitor)(jsFileName, { ...

unable to assign an array to a different array in typescript

I'm facing an issue with assigning values to the private kitems array in my class. Despite defining it as kitems:any[], when I try to assign a value using this.kitems = items; and then log this.kitems, it shows up as an empty array. createprofile() { ...

What is V8's approach to managing dictionaries?

After attending V8 presentations, it became clear to me that it optimizes constructions such as the one below by tagging a type object: function Point(x, y) { this.x = x; this.y = y; } I am curious about what happens if I were to return an object (JS ...