Check for duplicate in AngularJS and replace with larger duplicate

I have this piece of code where I am currently checking for duplicates using the isDuplicate boolean. However, I now want to enhance my code by comparing another property called colorId and then setting the isBigger property for the larger one :) Do you have any suggestions on how I can achieve this? Thank you in advance!

Below is the snippet of code:

$scope.verifyDuplicate = function() {
  var names = [{
    "order": 1,
    "name": "a",
    "shortName": "a",
    "isDuplicate": false,
    "categoryId": 15070,
    "colorId": 50
  }, {
    "order": 2,
    "name": "s",
    "shortName": "s",
    "categoryId": 15071,
    "colorId": 51
  }, {
    "order": 3,
    "name": "h",
    "shortName": "g",
    "focused": 1513262627570,
    "isDuplicate": true,
    "categoryId": 15074,
    "colorId": 54
  }, {
    "order": 4,
    "name": "h",
    "shortName": "h",
    "isDuplicate": true,
    "categoryId": 15075,
    "colorId": 59
  }];
  
  var sorted, i;

  sorted = names.concat().sort(function(a, b) {
    if (a.name > b.name)
      return 1;
    if (a.name < b.name)
      return -1;
    return 0;
  });
  
  for (i = 0; i < names.length; i++) {
    if (sorted[i].name !== '') {
      sorted[i].isDuplicate = ((sorted[i - 1] && sorted[i - 1].name === sorted[i].name)) || ((sorted[i + 1] && sorted[i + 1].name === sorted[i].name));
    }
  }
};

Answer №1

If you want to implement a Generic function that can sort an array of objects based on any key, you can use the following function:

$scope.sortByKey = function(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
    });
};

With this function, you have the capability to sort the array of objects by any key and also set the property "isLargest" to true. The code snippet below demonstrates how to do it.

$scope.verifyDuplicate = function() {
  var names = [{
    "order": 1,
    "name": "a",
    "shortName": "a",
    "isDuplicate": false,
    "categoryId": 15070,
    "colorId": 50
  }, {
    "order": 2,
    "name": "s",
    "shortName": "s",
    "categoryId": 15071,
    "colorId": 51
  }, {
    "order": 3,
    "name": "h",
    "shortName": "g",
    "focused": 1513262627570,
    "isDuplicate": true,
    "categoryId": 15074,
    "colorId": 54
  }, {
    "order": 4,
    "name": "h",
    "shortName": "h",
    "isDuplicate": true,
    "categoryId": 15075,
    "colorId": 59
  }];
  
  var sorted;
  sorted = $scope.sortByKey(names , "colorId");
  
  //Checking if multiple objects have the largest value
   for(var i = 0; i< sorted.length;i++){
     if(sorted[i] === sorted[0]) sorted[i]["isLargestColorId"] = true;
     else break;
   }
  
};

Answer №2

Utilize the latest ES6 functionalities

Determine the object with the biggest color ID and then set the isBigger property to true

 const names = [{
    "order": 1,
    "name": "a",
    "shortName": "a",
    "isDuplicate": false,
    "categoryId": 15070,
    "colorId": 50
  }, {
    "order": 2,
    "name": "s",
    "shortName": "s",
    "categoryId": 15071,
    "colorId": 51
  }, {
    "order": 3,
    "name": "h",
    "shortName": "g",
    "focused": 1513262627570,
    "isDuplicate": true,
    "categoryId": 15074,
    "colorId": 54
  }, {
    "order": 4,
    "name": "h",
    "shortName": "h",
    "isDuplicate": true,
    "categoryId": 15075,
    "colorId": 59
  }];

const biggerColorId = Math.max(...names.map(o => o.colorId));

const objOfBiggerColorId = names.find(o => o.colorId === biggerColorId);

objOfBiggerColorId.isBigger = true; // Set isBigger property to true for the object with the biggest color ID

// alert(JSON.stringify(objOfBiggerColorId))
console.log('objOfBiggerColorId ' + JSON.stringify(objOfBiggerColorId))


// alert(JSON.stringify(names))
console.log('names ' + JSON.stringify(names))

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

Activate function upon closure of window.open

I'm facing an issue where I need to load a URL in window.open that saves some cookies in my browser. After the window.open is closed, I want to access those cookies but I haven't been able to find a way to do it. I've tried the following cod ...

When scrolling the page, the Circle Mouse Follow feature will dynamically move with your cursor

Hey everyone! I'm currently working on implementing a mouse follow effect, but I'm facing an issue where the circle I've created moves along with the page when scrolling, instead of staying fixed to the mouse. Any suggestions or tips would b ...

Learn how to pass a JavaScript variable value to a PHP variable effectively

I have created a JavaScript variable and set it to a value. <script> var points = 25; </script> Now, I need to access this value in PHP for some specific reason but I am unsure how to accomplish that. ...

Enhance your user interface with Twitter Bootstrap and Angular.js by implementing a dynamic drop-down feature

How can I add a dropdown to a tab using angular.js and bootstrap? Here is the code I have: <tabset class="nav nav-tabs centered-tab sub-nav"> <tab heading="Bio" class="dropdown-toggle" > <ul class="dropdown-menu"> <li ...

Clicking on a specific month results in displaying only one row from the database rather than showing all rows associated with that particular month

I am facing an issue with my calendar feature on the website. The problem is that when I click on a specific month, it should display all the data associated with that particular month. However, the current code does not seem to work as expected. For insta ...

Issue: subscribe function is not definedDescription: There seems to be an

I'm currently trying to retrieve a value from an array based on a specific element, and then finding the exact matching element. Unfortunately, I've encountered an error with this.getProduct(name1: string) function even though I have already impo ...

Managing value state with several Formik forms within a single component

I'm currently in the process of constructing a web page using React and Formik. Within this form page, I have integrated three distinct Formik forms that are conditionally displayed based on a switch statement. The reason behind structuring it this wa ...

Before clicking the submit button, send field values using Ajax

Is it possible to send values using ajax before submitting form data with a submit button? I have the code below. It successfully reaches the success function, but I am unable to retrieve the posted data. Any ideas on how to solve this issue? Your help an ...

Arrange components within the form

Just started experimenting with this a few days ago. In my form, there is a text field and a button that I want to align side by side at the center of the form. .row { width: 100%; margin-bottom: 20px; display: flex; flex-wrap: wrap; } .col-6 { ...

Revamp your AngularJS controller for a fresh new look

How can a controller be refreshed in Angular? Take into account the scenario below: <div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div> <script> var ws = new WebSocket(something, something); function MsgCtrl($sco ...

Using the increment operator within a for loop in JavaScript

this code snippet causes an endless loop for (let i = 0; ++i;) { console.log(i) } the one that follows doesn't even run, why is that? for (let i = 0; i++;) { console.log(i) } I want a thorough understanding of this concept ...

Having trouble retrieving data from getters in the Vue store while inside a template

Within my component, I have set up computed properties that are supposed to display text for blopp and blipp. However, while blopp is working fine, blipp is not showing anything. The end goal is to have blipp generate a list of strings from the store state ...

Accessing the req object in Node.js using Express

Currently, I am attempting to redefine the function send in order to include an express-session value with each response. Unfortunately, I seem to be encountering issues accessing the variable req within the definition of send. 01| let app = express(); 02| ...

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...

Receiving a response from an XMLHttpRequest() within a function

I've come across a situation where I have a function called isOnline(), and here's how it looks: function isOnline() { var request=new XMLHttpRequest(); request.onreadystatechange=function() { if(request.readyState==4) { ...

Is there a way to set up a global web socket in NextJs?

I recently completed a tutorial on setting up a socket chat app, which I found at the following link: tutorial link. While I have successfully managed to get the system up and running, I'm facing an issue with exporting the front-end socket from the i ...

Add a hashbang #!/ to AngularJS $location.path for the URL

Attempting to utilize AngularJS $location to adjust the browser's URL by doing this: $location.path("/post").search({ id: post.id }); However, every time I try, the URL ends up looking like http://localhost:5000/#!/post?id=0 instead of http://lo ...

Enable lodash access throughout a React Native application

Is it possible to have lodash automatically accessible in all files within a React Native project without needing to import it every time? ...

How can I access specific values from a table generated with a PHP array using jQuery?

Currently, I am working on a page where users can upload documents. Once uploaded, these docs are stored in a folder and their location is updated in a table for reference. Now, when I navigate to an edit page, I use PHP to query the database and display t ...

Transforming an unconventional date format into a proper date representation

I have a spreadsheet with over 100,000 dates stored in the following format: Thursday 29th of October 2015 01:06:21 PM Converting these dates into a usable format is proving to be a challenge. Whether it's YYYY/MM/DD or any other standard format, I ...