Filter out elements from a JavaScript array that are present in a different array

In my Angularjs application, I have created a JavaScript function to remove duplicate items from one array which also exist in another array. The function works by iterating through arr1 and checking if each item is present in arr2. If a match is found, the item is removed from arr1.

// Remove duplicate items from array1 based on array2
        $rootScope.removeArrayDuplicated = function (arr1, arr2) {
            console.log('before');
            console.log(arr1);
            for (var i = 0; i < arr2.length; i++) {
                Inner:  for (var j = 0; j < arr1.length; j++) {

                    if (arr2[i].name == arr1[j].name) {
                        console.log("inside " + arr2[i].name + " " + arr1[j].name);

                        arr1.splice(j, 1);
                        j--;
                        break Inner;
                    }
                }
            }
            console.log('after');
            console.log(arr1);
            return arr1;
        }

After running the function, I noticed that both the before and after arrays are displaying the same values. I suspect there might be an error in my logic. Could someone please help me identify and correct it?

*Note: The arrays consist of JSON objects.

Answer №1

Success! This solution should do the trick.

$scope.removeArrayDuplicates = function(arr1, arr2) {
  return arr1.filter(item => !(arr2.some(item2 => item.name === item2.name)));
}

Check out a live demo here.

Below is the ES5 code transpiled using Babel:

$scope.removeArrayDuplicates = function (arr1, arr2) {
  return arr1.filter(function (item) {
    return !arr2.some(function (item2) {
      return item.name === item2.name;
    });
  });
};

Answer №2

Do you need to modify the original array, or is it acceptable to create a new output array?

If generating a new output array is permitted, here is a function that accomplishes this:

    $rootScope.removeArrayDuplicates = function (array1, array2) {
        var outputArray = [];

        for (var i = 0; i < array2.length; i++) {
            var isDuplicate = false;
            Inner: for (var j = 0; j < array1.length; j++) {

                if (array2[i].name == array1[j].name) {
                    console.log("matching names: " + array2[i].name + " and " + array1[j].name);
                    isDuplicate = true;
                    break Inner;
                }
            }

            if (!isDuplicate) {
                outputArray.push(array2[i].name);
            }
        }
        return outputArray;
    }

Answer №3

If you want to easily filter out duplicate items from two arrays, you can use Array.prototype.filter:

var newArray = array1.filter(function(element) {
  return array2.indexOf(element) == -1;
});

Instead of comparing item names for deduplication, consider storing the names in a map for quicker retrieval:

var removeDuplicates = function(array1, array2) {
  var nameMap = {};
  array2.forEach(function(element) {
    nameMap[element.name] = true;
  });
  return array1.filter(function(element) {
    return !!nameMap[element.name];
  });
});

This optimized version operates at O(N) complexity compared to the initial solution's O(N^2).

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

AngularJS: resolving route dependencies

I have a variable $scope.question that contains all the questions for the page. My goal is to loop through the questions page by page. To achieve this, I created a function called questionsCtrl and I am calling this function in the config while setting up ...

Blocking the space bar in JavaScript is a useful technique that can be

I'm in the process of developing an application and I'm looking to prevent the space bar from scrolling my page My framework of choice is VUE, and I am trying to trigger a method using an event handler However, when I attempt to call the ' ...

Transitioning from the Homepage to the Posts page triggered a problem due to the impact of jQuery code used on the Homepage

Recently, I integrated some jQuery code into my react code to create a fading effect on the home page components when scrolling. While it works perfectly on the homepage, I encountered an error when navigating to another page such as the 'all posts&ap ...

jQuery - can you identify which specific object from the entire set this is?

I am curious if there is a simple method to identify which DOM object I have when it is also part of another set of objects. To illustrate, let's consider the following scenario: There are 5 div elements: <div id="1"></div> <div id="2 ...

I have chosen not to rely on Media Query for ensuring responsiveness in my Angular 2 application, and instead opted to utilize JavaScript. Do you think this approach is considered a

I am in the process of ensuring that my app is fully responsive across all screen sizes. Instead of relying on Media Query, I have chosen to use JavaScript with Angular 2 to achieve this responsiveness, utilizing features such as [style.width], *ngIf="is ...

Reliably analyzing text to generate unprocessed HTML content

My input text in a textarea is structured like this: This is some sample text./r/n /r/n This is some more sample text. I want to format it for display as follows: <p>Here's some text.</p> <p>Here's some more text.</p> ...

Delete items within the first 10 minutes of shutting it down

Is there a way to temporarily remove a newsletter element for 10 minutes after closing it on a webpage? The idea is that once the panel is closed, it should stay hidden even if the page is refreshed within that timeframe. I was considering using local stor ...

Error message from @firebase/database: The Firebase Database URL could not be identified. Please ensure that you provide a Project ID when initializing firebase.initializeApp(). This issue is specific

Currently, I am in the process of setting up a live chatroom. Initially, everything was working perfectly on my first attempt. However, when I had to focus on another task and returned to this project, I encountered an error message stating that I cannot i ...

What is the secret behind the performance enhancement of Clojure's "array swap trick" in improving LCS efficiency?

In continuation of the insights shared by @cgrand in response to the query "Clojure Performance For Expensive Algorithms," I have been delving into his suggestions and attempting to implement some of his techniques for optimizing performance in my own Cloj ...

Distinct hash values

Within my hash, I have arrays containing objects with unique attributes: hash = { "key1" => [object11, object12, object13], "key2" => [object21, object22, object23] } Each array consists of objects from the same class, each having a source attr ...

I'm having trouble retrieving the precise coordinates of a mouse click. Can anyone help troubleshoot my code?

When attempting to display something at the exact place where a mouse click occurs, I utilized the following code snippet: $('#my-graph').mousedown(function(evt){ // show object at: var x= evt.screenX, y=evt.screenY; //or sho ...

Having trouble accessing a JSON object with Typescript in an Angular 2 project

Something strange is happening with my code. I am working with a JSON object: {"login":"admin","name":"Admin"} And this is the relevant part of my code: private _userData: User; ... private getUserData() { this._userInfoService.getUserInfo() ...

Encountering the error message "Undefined variable '$'" in a script that is loaded after jQuery

My code is simple - it loads jQuery first, followed by a script that uses the $ syntax. However, I keep encountering the error: ReferenceError: $ is not defined Initially, I suspected that the async attribute on the script tag was the issue, but changi ...

Having trouble with the Ajax JS/PHP Image Upload feature malfunctioning

Despite trying various methods and researching extensively on StkOvfl and W3 Specifications, I am still unable to solve this issue. The problem lies with a form input I have: <input type="file" multiple accept="image/*" id="item-image-upload" > In ...

Updating Nested Arrays in MongoDB

I am attempting to modify the quantity of the first item in the first order. Here are the insert and update instructions: db.client.insertOne({ "noClient":1, "nomClient":"John Doe", "noTéléphone":"1234567 ...

Manipulating class properties in AngularJS from a controller

I won't dwell on the reason for this (it's required to override some behavior in Angular Material that is causing issues in Safari), but here is what I am attempting to accomplish: HTML: <style> .changeme{ height: 300px; } </st ...

Strategies for ensuring completion of internal promises

When using fs.readdir to retrieve a list of directories and then again within the callback to get a list of "subpages" in each directory, I find myself wanting the first callback to wait until the second one is completed. Unfortunately, I'm unsure of ...

Unraveling request parameters in Angular: A step-by-step guide

I am looking to create a unique URL structure like http://mydomain.com/token/abc12345, where abc12345 is a variable parameter that needs to be extracted. Upon detecting this URL in Angular, I want to extract the token, perform a database lookup, populate ...

Ways to switch out the background image using jQuery

I am currently using jQuery to dynamically change the background image of a web page. Right now, I have implemented two separate buttons that toggle between Image A and Image B. By default, Image A is displayed on the page. My goal is to enhance this func ...

What is the best way to organize code into separate files while utilizing a module that needs to be included in every file?

In this particular scenario, I am utilizing a headless browser with Puppeteer Chrome and MongoDB. Take a look at the following code snippet: var browser = await puppeteer.launch() var page = await browser.newPage() var db = await MongoClient.connect(" ...