Discover distinct and recurring elements

Having two sets of JSON data:

vm.userListData = [{
        "listId": 1,
        "permission": "READ"
    }, {
        "listId": 2,
        "permission": "WRITE"
    }, {
        "listId": 2,
        "permission": "READ"
    }, {
        "listId": 3,
        "permission": "READ"
    }, {
        "listId": 3,
        "permission": "WRITE"
    }, {
        "listId": 4,
        "permission": "WRITE"
    }, {
        "listId": 5,
        "permission": "WRITE"
    }]
vm.userComplementaryList = [{
    "listId": 1,
    "confidentiality": "PUBLIC",
    "listName": "List name here..1",
    "permission": "WRITE"
}, {
    "listId": 2,
    "confidentiality": "PUBLIC",
    "listName": "List name here..2",
    "permission": "READ"
}, {
    "listId": 3,
    "confidentiality": "CONFIDENTIAL",
    "listName": "List name here..3",
    "permission": "WRITE"
}, {
    "listId": 4,
    "confidentiality": "CONFIDENTIAL",
    "listName": "List name here..4",
    "permission": "WRITE"
}, {
    "listId": 5,
    "confidentiality": "CONFIDENTIAL",
    "listName": "List name here..5",
    "permission": "READ"
}]

I am filtering and pushing unique values into one array, and duplicated values into another. Here's my code:

vm.listForGrid = [];
vm.listForDropDown = [];

(function(){
    for(var i = 0; i < vm.userComplementaryList.length; i++) { 
        for(var j = 0; j < vm.userListData.length; j++) {   
            if( (vm.userComplementaryList[i].listId == vm.userListData[j].listId) && (vm.userComplementaryList[i].permission == vm.userListData[j].permission) ) {
                vm.listForGrid.push(vm.userComplementaryList[i]);
            }
            else {
                vm.listForDropDown.push(vm.userComplementaryList[i]);
            }
        }
    }
})();

The vm.listForGrid has the correct values, but I'm facing duplications in vm.listForDropDown. I need to implement a break statement to resolve this issue.

Please note that the duplicates occur when the listId and permission are the same in both arrays.

Thank you!

Answer №1

If you have permission, consider using a hash table for reference. This way, you can streamline the sorting process by utilizing just a single loop instead of nested loops.

var vm = {},
    permissions = {};

vm.userListData = [{ "listId": 1, "permission": "READ" }, { "listId": 2, "permission": "WRITE" }, { "listId": 2, "permission": "READ" }, { "listId": 3, "permission": "READ" }, { "listId": 3, "permission": "WRITE" }, { "listId": 4, "permission": "WRITE" }, { "listId": 5, "permission": "WRITE" }];
vm.userComplementaryList = [{ "listId": 1, "confidentiality": "PUBLIC", "listName": "List name here..1", "permission": "WRITE" }, { "listId": 2, "confidentiality": "PUBLIC", "listName": "List name here..2", "permission": "READ" }, { "listId": 3, "confidentiality": "CONFIDENTIAL", "listName": "List name here..3", "permission": "WRITE" }, { "listId": 4, "confidentiality": "CONFIDENTIAL", "listName": "List name here..4", "permission": "WRITE" }, { "listId": 5, "confidentiality": "CONFIDENTIAL", "listName": "List name here..5", "permission": "READ" }];

vm.listForDropDown = [];

vm.userListData.forEach(function (p) {
    permissions[p.listId] = permissions[p.listId] || {};
    permissions[p.listId][p.permission] = true;
});

vm.listForGrid = vm.userComplementaryList.filter(function (a) {
    if (permissions[a.listId] && permissions[a.listId][a.permission]) {
        return true;
    }
    vm.listForDropDown.push(a);
});

console.log(vm.listForGrid);
console.log(vm.listForDropDown);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

here is a shorter version that utilizes array.some method

vm.userComplementaryList.forEach(function(vCom) {
    vm.userListData.some(function(vUser) {
        return (vCom.listId == vUser.listId && vCom.permission == vUser.permission);
    }) ? vm.addToGridList(vCom) : vm.addToDropDownList(vCom);
})

Answer №3

After some careful consideration, I came up with the following solution:

(function(){
    for(var i = 0; i < vm.userComplementaryList.length; i++) { 
        var found = false;
        for(var j = 0; j < vm.userListData.length; j++) {   
            if( (vm.userComplementaryList[i].listId == vm.userListData[j].listId) && (vm.userComplementaryList[i].permission == vm.userListData[j].permission) ) {
                found = true;
                break;
            }
        }
        if(found) {
            vm.listForGrid.push(vm.userComplementaryList[i]);
        }
        else {
            vm.listForDropDown.push(vm.userComplementaryList[i]);
        }
    }
})();

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

Unusual behavior exhibited by AngularJS when working with Float32Arrays

After working with Float32Array values in AngularJS, I have noticed some unexpected behavior. During my testing, I encountered the following scenarios: angular.module("myApp", []).controller("myCtrl", function($scope) { $scope.n = 0.2; // Displays as 0 ...

Tips for adding up information in a JSON array received from the controller and passed to the view in Laravel

I have encountered a problem with the JSON array provided below: $results = [ { proj_name: rental, act_name: income, amount: "1000" }, { proj_name: rental, act_name: expend, amount: "-2000" }, { proj_name: r ...

Utilize UI-Router $stateProvider in Angular run block for Promise Resolution

UI-Router has different capabilities compared to Angular's ngRoute. It not only supports all the features of ngRoute but also provides additional functionalities. I am transitioning my Angular application from ngRoute to UI-Router. However, I'm ...

How can I organize data from A to Z in alphabetical order in React Native when the user chooses the A to Z option from the dropdown menu?

I am working on a screen that can display up to 1000 data retrieved from the API. Here is the image: https://i.sstatic.net/ErbDD.png Now, I have implemented a drop-down box where users can select alphabetically from A to Z. After selecting an alphabetic ...

Angular Protractor testing: achieving precise column name matching

I am new to writing protractor tests and currently navigating my way through it. The angular code I am trying to test looks like this: <tr ng-repeat="identifier in contentIdentifiers"> <td>{{identifier.contentIdentifier}}</td> & ...

Unexpected anomaly with Jquery's after() method

Currently, I am working on the following task: I want to dynamically add a new student to a table of existing students using AJAX when a student is added through my user interface. The process involves sending the UI input fields to the controller, which ...

Prevent the opening of tabs in selenium using Node.js

Currently, I am using the selenium webdriver for node.js and loading an extension. The loading of the extension goes smoothly; however, when I run my project, it directs to the desired page but immediately the extension opens a new tab with a message (Than ...

Exploring Elasticsearch: Uncovering search results in any scenario

I've been working on a project where my objective is to receive search engine results under all conditions. Even if I enter a keyword that is not included in the search data or if it is an empty string, I still want to get some kind of result. How can ...

Using AngularJS to hide elements within a nested dictionary structure

My dictionary structure is as follows: var data = { a: [1, 2, 3, 4, 5], b: [ [1, 2], [3, 4], [5, 6] ] }; Currently, I am using ng-hide to hide an element if the value 2 exists in data->a. Here's how it's implemented: <i ...

The alternating colors in the sorting table are not visible due to the divs being hidden with the display set

I've come across a problem that has me stumped. So, there are two sorting filters on a table and one of them hides rows that don't apply, messing up the alternating colors. Take a look at the function that sorts and the CSS below. The issue is pr ...

React's JS is having trouble accepting cookies from the express server

I've encountered an issue where sending cookies from my express server using res.cookie() is not working with the front end. Even though I include {withCredentials:true} in the get requests, the cookies are not being set in the browser's applicat ...

The proper way to compare numbers in JavaScript

I need to determine the color for my legend by comparing two values without using ceil, floor, or round functions. The color is based on a color table with point and RGB values. The backend provides points like 0.4607441262895224, 0.5500956769649571, etc. ...

What is the best way to rephrase a sentence that contains a double negative

Figuring out how to negate a condition often requires hours of trial and error to avoid breaking anything. Is there any method for negating conditions other than relying on intuition? For instance: //x and y are whole numbers !((x<9) && (y&l ...

Node.js application with decoupled Redis client

In my node.js app, I am utilizing Redis for user caching. Once a user logs in, their information is cached and accessed on subsequent requests to determine their access level. This allows the client to receive personalized information and views based on th ...

Assigning event to the body element

Is there a way to bind an event to the entire page, specifically the html or body tag? I am trying to achieve the following: document.addEventListener('mousemove', function() { alert('a'); }); I want an alert to be triggered whenever ...

showing a pop-up message when a specific javascript function is triggered

Here is a unique code snippet showcasing a customized dialog box created with HTML, CSS, and JavaScript. The dialog box is displayed when a button is clicked. <!DOCTYPE html> <html> <head> <style> /* Custom Modal Styles */ .modal { ...

"Underscores in an array of primary keys serve as markers for

I want to filter a list of objects using underscore based on their primary key being included in a specific array of primary keys. list = [object{pk: 1}, object{pk: 2}, object{pk: 3}] primary_key_list = [1,2] The desired outcome is to return [object{pk: ...

How can I apply a texture to a 3D rectangle in THREE.js?

I am attempting to create a 3D box in THREE.js that represents a box made up of 2x4 Legos, measuring 24 pieces wide by 48 pieces long and an unspecified number of pieces tall. I have created a texture displaying this pattern using random colors: https://i ...

Sending an array of JSON data to an MVC controller property for model binding

I need assistance with passing an integer array using jQuery Ajax. It seems like my controller is not receiving the data properly. Here is the jQuery AJAX call: var box = {MECallButtons: R_MainEntranceButtons } $.ajax({ type: "POST", url: "/Home ...

What is the best method for obtaining non-null values for the jsonSerialize interface in PHP?

My class is using the jsonSerialize method in php After implementing the jsonSerialize method, my class returns only non-null variables by utilizing get_object_vars($this). public function JsonSerialize() { $vars = get_object_vars($this); r ...