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

Steps to close a socket upon session expiration

I am currently working on a small express application that also incorporates a socket program. Everything works perfectly when a user successfully logs in - it creates the session and socket connection seamlessly. However, I encountered an issue where eve ...

Using the @ symbol in jQuery within an MVC framework can be achieved by first ensuring that

I'm attempting to incorporate the @ symbol into a JavaScript if condition, but I keep receiving an error. if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) { alert('yes'); ...

The XMLHttpRequest() function throws NS_ERROR_FAILURE when sending requests to localhost using either an absolute or relative path

Encountering an error in Firefox 31 ESR: Error: NS_ERROR_FAILURE: Source file: http://localhost/Example/scripts/index.js Line: 18 Similar issue observed on Internet Explorer 11: SCRIPT5022: InvalidStateError The script used for AJAX function call i ...

The nodejs events function is being triggered repeatedly

I have been developing a CMS on nodejs which can be found at this link. I have incorporated some event hooks, such as: mpObj.emit('MP:FOOTER', '<center>MPTEST Plugin loaded successfully.</center>'); Whenever I handle this ...

The function webpack.validateSchema does not exist

Out of the blue, Webpack has thrown this error: Error: webpack.validateSchema is not defined Everything was running smoothly on Friday, but today it's not working. No new changes have been made to the master branch since Friday. Tried pruning NPM ...

[Vue alert]: Component mounting failed due to usage of mixin with a parameter

For the past day, I've been facing difficulties creating a Vue mixin with a parameter. When attempting to do so, I encounter a [Vue warn]: Failed to mount component: template or render function not defined error. Below is my JS file which includes the ...

Using Next.js with Firebase emulators

I've been struggling to configure Firebase's V9 emulators with Next.js, but I keep running into the same error message. See it here: https://i.stack.imgur.com/Uhq0A.png The current version of Firebase I'm using is 9.1.1. This is how my Fir ...

Oops! The angular app encountered an error: TypeError - it cannot read property '0' of undefined. Time to debug

Having difficulty grasping the source of an error, as the html side is able to read list[3].main.temp without any issues. However, in the second loop of the generateList function, I encounter an error specifically on $scope.list[i].main.temp, which throws: ...

Mixing box-shadow and blur filters can result in unusual artifacts appearing in Webkit browsers

Recently, I encountered an intriguing and frustrating bug in WebKit browsers. Consider a scenario where there is a parent DIV (let's say .wrapper) and a child DIV (.main). You apply a box-shadow on the .main DIV and a blur filter on the .wrapper DIV. ...

Retrieve a boolean value through an Ajax call from a C# function using T4MVC

I have a search bar on my website with the following code: <form onsubmit="return IsValidCustomer()"> <input class=" sb-search-input" placeholder="Search for a customer..." type="text" value="" name="search" id="search"> <input cl ...

Is NG-True-Value exclusively for string literals?

I am attempting to utilize the ng-true-value directive with expressions or objects: I experimented with these options: ng-true-value={{selection}} ng-true-value="selection" ng-true-value="{{selection}}" Unfortunately, none of these approaches h ...

Leveraging dependency injection in Angular 2+ with pre-loaded models

I desire the ability to create an instance of a model using a constructor while also providing injected services to that model. To clarify, I envision something like this: var book = new Book({ id: 5 }); // creates instance, sets id = 5 book.makeHttpCa ...

Timeout function is failing to trigger the digest cycle

When calling a chrome function that runs asynchronously, the digest cycle needs to be run in order to update scope variable values in the view. While attempting to achieve this with $timeout and $evalAsync, I encountered issues. Directly calling $scope.$ap ...

How to access the api variable in JavaScript

When attempting to retrieve variables from an API object, I encountered the obstacle of them being nested inside another object named "0" in this particular case. Here is a screenshot from the console: enter image description here Below is the JavaScrip ...

Examine each of the elements in the ng-repeat loop

When it comes to the first prematchGame having a value of 1 and 2, I encounter an issue where the first element does not have these values, but the 3rd and 4th elements do. (refer to the image) Is there a way for me to check if the 1st element in ng-repea ...

How can I trigger my function in jQuery after inputting into the jQuery text field?

Looking for advice on implementing a function in jQuery for a text field that is not working as expected. The code works fine when creating a text field in HTML, but encounters issues with the jQuery text field. <!DOCTYPE html> <html> <body ...

Skipping every third index in a JQuery .each loop after removing an element

I have a project where I need to display elements in rows of 4, and when an element is deleted, I want the remaining elements to shift up. To achieve this, I am currently assigning a class "last" to every fourth item after a deletion and inserting a spacer ...

What is the best way to calculate the number of days that have passed since a certain

Hey there, I've got this 10 Dec, 2019T14:07:21 date format from the backend. My goal is to determine how many days ago it was. For example, today is the 20th, so if the date is today's date, it should show as 0 days ago. ...

Retrieve the values from hidden input fields that share the same name

How do I retrieve values from cName inputs? <form method="post" action=""> <input type="hidden" name="cName" value="test1" /> <input type="submit" name="get" /> </form> <form method="post" action=""> <input type="hi ...

"Implementing jQuery to dynamically set the href attribute for a link when

My website features a tabbed menu that displays content from various WordPress categories including Cars, Trucks, and Buses. The active tab is randomly selected each time the page is reloaded. However, there seems to be an issue with the "View More" button ...