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

What are the necessary steps for incorporating Payment/Bank transactions into an e-commerce platform?

Right now, I'm utilizing HTML, CSS, jQuery, and some JavaScript to develop a website. As I work on creating the store section, I find myself unsure of how to incorporate payment methods and all related features. Are there any free "pre-built" systems ...

Uncover the mysteries of the pyramid and json

I am developing a web app using Pyramid that involves fetching data from the user, retrieving information from the backend based on the input values, and then displaying the results in a table format. The process includes the following steps: User enters ...

Updating state within a loop of properties in a React ComponentDidUpdate function

I have been working on a project where I needed to update the state after the componentDidMount lifecycle method. The props that I am expecting in the child component are only available at mount, so I can only update the state after that point. The only so ...

Control and manage AJAX POST requests in the controller

I'm currently working on implementing an ajax post request feature in my project. The goal is to have a button on my html page trigger a javascript event listener, which then initiates an ajax post request to receive some text data. However, I seem to ...

Disabling Immediate Row Checkbox in Angular Datatable Based on Column Data

Is there a way to prevent the checkbox in a row from being checked based on certain column data? In my datatable, I need to implement a condition where if firstname="Superman", then the checkbox for that particular row should be disabled to preve ...

Display more/hide less form using div elements in a NextJS project

Looking to create a hidden block of amenities on my hotel website that can be expanded and collapsed with buttons in NextJS using tailwind-css. How can I achieve this functionality? Example 1: https://i.stack.imgur.com/BbrUj.png Example-2: https://i.stac ...

Tips for managing Express.js callbacks and modifying an object's property from within a function

I am currently working with two JavaScript files. I have successfully retrieved data from MongoDB using the method bookDao.getActiveBookByCategoryId(). The Issue I Am Facing: Within the categoryDao.js file, I am attempting to update the resultJson.book_c ...

Mocking a React component with Jest's MockImplementation

Currently, I am in the process of testing a react component that renders another component. This secondary component makes an API call to fetch data which is then displayed on the screen. My goal is to understand how I can mock this particular component&ap ...

The peculiar behavior of Laravel's Eloquent relationship: it loses its object nature whenever any action is performed,

I have a unique and bizarre situation here. I possess activity logs for users, and my user model holds this particular relationship: public function recentUserActivityLogs() { return $this->hasMany(Log::class); } It's pretty straightforward, ...

Troubleshooting the issue of a callback function not properly updating state within the componentDidMount

I am currently utilizing Next.js and have the following functions implemented: componentDidMount = () => { //Retrieves cart from storage let self = this this.updateCart(Store.getCart(), self) ... } updateCart = (cart, self) => { ...

Angular's promise delay is failing to meet expectations

Unfortunately, I'm unable to display the complete code snippet here. However, I have come up with a summary of the issue I am facing. I have implemented a service and controller in my code. Within the service, I included a 2-second timeout for my gro ...

What is the process for integrating Internet Explorer 10 compatibility into a basic VueJs component?

I am facing an issue with a VueJs component that is not rendering in IE 10. Context: The Vue component I am working on is a company events list with basic filtering and sorting functionalities. Unfortunately, IE10 support is required for this project. Eve ...

I am facing an issue where an AJAX post to Express is not returning any data to req.query. I have tried various solutions but nothing seems to

I have encountered an issue with my setup where the body is empty when sending data through ajax. In Chrome's network tab, I can see the post and content with the correct payload: {"EventName":"asd","PrivacyLevel":1,"TypeInt":1,"ExpectedDate":"asd"," ...

Adding the unzip feature is not within my capabilities

I am a novice Japanese web developer. Unfortunately, my English skills are not great. I apologize for any inconvenience. I am interested in utilizing this specific module: https://www.npmjs.com/package/unzip To do so, I executed the following commands ...

Looking for a sophisticated approach in Spring MVC to manage the escaping and unescaping of strings being passed to the Front End

Currently, I am in the process of developing a web application utilizing Spring MVC. This project involves retrieving multiple objects from the Database, each containing strings as attributes. It's worth noting that I have no control over the format o ...

Steps for updating the homepage to display a personalized welcome message to the user after logging in and redirecting using node.js and

Upon arriving at the homepage, simply click on the sign-in button. Once redirected back to the home page, you will notice a personalized greeting saying 'Welcome [user]'. Wondering how to achieve this? It's as simple as changing the text fro ...

Tips for making a Python list without utilizing the range function in For Loops

If we take the string myString = "ORANGE" How can we implement a loop that displays each character with its position as shown below? 1O 2R 3A 4N 5G 6E I'm facing some confusion on how to achieve this without utilizing range. ...

Utilizing Ajax for submitting data in a Spring application

I'm attempting to send a PUT request to the controller using AJAX. Here is my code: $().ready(function(){ $('#submit').click(function(){ var toUrl = '/users/' + $('#id').val() + '/profile'; ...

Angular component testing with unit tests

I am currently working on unit testing my component controller and encountering some errors. Can someone assist me in identifying the issue? Here are the dependencies I am using: angular 1.5.6 angular-mocks 1.5.7 mocha 2.5.3 karma 0.13.22 Errors: moda ...

Facing issues with ReactCSSTransitionGroup as transitionAppear feature is not functioning

I'm having trouble with the appearance and disappearance of notifications. The transitionAppear property doesn't seem to be working as expected. I'm adding the notification popup item to the onBlur event. The animation for the leave event wo ...