Finding the difference between two arrays using nested loops

function filterArrayDifference(arr1, arr2) {
    let result = [];
    for (let i = 0; i < arr1.length; i++) {
        let isUnique = true;
        for (let j = 0; j < arr2.length; j++) {
            if (arr1[i] === arr2[j]) {
                isUnique = false;
                break;
            }
        }
        if (isUnique) {
            result.push(arr1[i]);
        }
    }
    return result;
}

console.log(filterArrayDifference([1,2,2,3], [1])); // output: [2,2,3]
console.log(filterArrayDifference([1,2,2,3], [1,2]); // output: [3]

Attempting to address the issue of unwanted outputs caused by multiple elements in 'arr2' when finding array difference.

Answer №1

It's worth considering utilizing a Set along with Array#filter.

const 
  list1 = [1, 5, 3, 7, 9],
  list2 = [5, 1, 10, 13],
  set = new Set(list2),
  result = list1.filter((item) => !set.has(item));

console.log(result);

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

unable to retrieve the properties of req.user

Currently, I am working on developing a multiplayer game that involves a login system. Within my app.js file, the following code snippet allows me to access user information: app.use(function (req, res, next) { res.locals.success_msg = req.flash('s ...

Error message: Unable to locate module when using a variable to import an image in React

I've encountered an issue with my React code that I can't seem to figure out. I am integrating the Accuweather API and trying to display the weather icon on my app. Initially, everything seemed to be working fine as I constructed the image path l ...

Trying to populate an array with user input from the console, but every second element ends up getting set as an empty value

I'm encountering an issue while trying to populate an array with console input and then display it in reverse order. For some reason, every other element is being assigned a blank value, resulting in missing lines of input during output. The current a ...

Preventing Double Click Events on jQuery Spinner

I have been working on an option picker, but now there is a new requirement to make the options configurable. While this shouldn't be too difficult, I am facing some issues with the option picker: Currently, when an item is double-clicked, it will ge ...

What are the best methods for protecting a soda?

My code is in strict mode, and I am encountering an issue with the following snippet: const a: string[] = []; // logic to populate `a` while (a.length > 0) { const i: string = a.pop(); // This line is causing an error console.log(i); // additio ...

What is the best way to eliminate products that have already been utilized?

Take a look at my code snippet. $(function() { $("#tags input").on({ focusout: function() { var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig, ''); // only allow certain characters if (txt) $("<span/& ...

Use Material UI TextField to prompt an email client or make a phone call

I am facing an issue with a MaterialUI TextField component. In certain situations, the TextField is disabled and I want it to be clickable as if it were an anchor tag leading to a phone number or email address. However, it seems that making the input behav ...

Verify the changing text within a Span tag with the use of Selenium in Java

Can anyone assist me in creating a logic to verify a dynamic text? The text within the tag below is constantly changing (to 6 distinct words), and I need to validate if those 6 unique words match the expected text. Is there a method to do this verification ...

What is the process for inheriting in JavaScript while also defining new prototype members as a singular object?

I find this code repetitive because it repeatedly uses Child.prototype: function Parent(a) { this.a = a; } function Child(a, b) { Parent.call(this, a); this.b = b; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = ...

Tips for organizing the outcome of a seamless web scraping operation with Apify and Puppeteer

Extracting data from a table on the designated URL using Apify and Puppeteer is my current goal: https://en.wikipedia.org/wiki/List_of_hedge_funds The desired outcome should be an array of objects. Each element in the array must represent a <tr> ro ...

Refreshing forms in Angular 2

I am attempting to retrieve values from forms using the submit event. However, I am encountering difficulty resetting those forms later on. I am using an id called "myForm" and an onclick function to try and achieve this. <form (Submit)="addMarker()" i ...

Setting the box width to "0" will actually render as a width of "1"

While attempting to create a box new THREE.BoxGeometry(opening.geometry.xLength, opening.geometry.yLength, opening.geometry.zLength) a situation arises where a box with 0 width is produced. new THREE.BoxGeometry(0, 1, 1) Surprisingly, it ends up render ...

JavaScript's inability to load images lazily poses a significant challenge

I'm having trouble implementing lazy loading for my images using JavaScript. When I change the html attribute from src to data-src, the images do not display at all. Additionally, when attempting to use an intersectionObserver to lazily load the image ...

Strategies for sending data in the body of a GET request in a React.js API

I'm having an issue passing data in the body of a GET type API request in my React.js app. Here is the code I am using, but the API isn't receiving any data. getUnits = ( key, text, code, limit, offset ) => { let data = JSON.st ...

Using lodash in JavaScript to flatten a nested object structure

I'm looking to flatten a hierarchical json structure. Here is an example of my json data: { "id": "111", "name": "v5", "define": { "system": "abc", "concept": [{ "code": "y7", "concept": [{ "code": "AGG", "di ...

Using the attribute data-ng-repeat along with the <option> tag allows for dynamic iteration and

Hello there, I am a beginner with AngularJS and I am struggling to understand how to create my <option> list. I would like my output to resemble the example in this fiddle: http://jsfiddle.net/XdpJv/ This is what my current code looks like: <se ...

Incorporate an ArrayList into a 2D ArrayList in Java

I am encountering an issue with my 2D ArrayList that I need to populate with multiple 1D ArrayLists. Here is the code snippet in question: ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>(); ArrayList<Strin ...

Error: The `gatsby require.resolve` function cannot locate the specified module when attempting

Currently, I am referring to the tutorial at and have already set up my gatsby-node.js file. Here is how my current directory structure looks like: public src -pages -templates --program_group.js static gatsby-config.js gatsby-node.js In my gatsby-node. ...

Guide to displaying nested maps in VueJS

After creating a map of maps structured like this: {year1:{topic1:[article1,article2]},year2:{topic1:{article3}}} I attempted to use v-for for iterating through this map but encountered difficulties. Upon printing the template, I noticed the output looke ...

Show repeated characters within a given string

After writing some code in C++ to identify duplicate characters in a string, I noticed an issue. If a character appears more than three times in the string, the code repeats that character multiple times in the output. For instance, with the input string ...