Strategies for removing duplicate items from an array of objects

My array consists of objects with the following structure:

$scope.SACCodes = [
    {'code':'023', 'description':'Spread FTGs', 'group':'footings'},
    {'code':'024', 'description':'Mat FTGs', 'group':'footings'},
    {'code':'025', 'description':'CONT. FTGs', 'group':'footings'},
    {'code':'025', 'description':'CONT. FTGs', 'group':'levels'},
    {'code':'023', 'description':'Trucks', 'group':'footings'}
]

I am looking to eliminate duplicates based on both the code and group values. The filtering process should not remove entries if only one of these properties is a match.

Answer №1

Here is a different approach inspired by TLindig's solution to a related question.

Implement a custom filter function on the scope:

$scope.uniqueFilter = function(value, index, self) { 
  codes = self.map(function(c) {return c.code});
  groups = self.map(function(c) {return c.group});
  return codes.indexOf(value.code) === index || groups.indexOf(value.group) === index;

Use the filter function within your ng-repeat or in any location where unique values are needed:

<div ng-repeat="c in SACCodes.filter(uniqueFilter)">code: {{c.code}} desc: {{c.description}} group: {{c.group}}</div>

Result:

code: 023 desc: Spread FTGs group: footings
code: 024 desc: Mat FTGs group: footings
code: 025 desc: CONT. FTGs group: footings
code: 025 desc: CONT. FTGs group: levels

Answer №2

Utilizing ES6 features.

let uniqueMap = new Map();

codes.forEach ( codeItem => {
    let key = codeItem.code + codeItem.group;
    if ( !uniqueMap.has( key ) ){
        uniqueMap.set( key, codeItem );
    }
});
codes= [ ...uniqueMap.values() ];  

Answer №3

Utilizing a helper hash, this script keeps track of processed combinations of code and group. It only adds new combinations to the retVal array;

function removeDuplicates() {
    var duplicates = {};
    var retVal = [];

    for (var i = 0; i < $scope.SACCodes.length; i++) {
       var sCode = $scope.SACCodes[i];
       var key = sCode.code +'/'+ sCode.group;
       if (!duplicates[key]) {
          retVal.push(sCode);
          duplicates[key] = sCode;
       }
    }
    return retVal;
}

Check out the live example here

In the future, consider using Object.values(duplicates); instead of retVal to streamline the code.

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

Searching for a client-side element within an update panel using code-behind: A step-by-step guide

While working on a user control in asp.net, I encountered a significant challenge in locating the client side HTML element positioned within an update panel. The .ascx file contains the following code snippet: <asp:UpdatePanel ID="UpdatePanel1" runat= ...

Safari Displaying Error Message "Unhandled Promise Rejection: [object DOMError]" While Playing MP4 Video

I am facing an issue with playing a group of MP4 videos on hover in a container. You can view a demonstration by clicking the link below: While this functionality works smoothly in Chrome, it seems to be causing problems in Safari. Upon hovering, the vide ...

Is there a concept in JavaScript that includes a data structure called a "matrix" with elements arranged in a grid-like format accessed by

I'm not familiar with the terminology, but I'd like to simplify it: var topicList1 =['hello','hallo', ..., 'hej']; var topicList2 =['a','b',...,'c']; ... var topicList999 =['x,&apo ...

Difficulty with timing in React.js when rendering content from an Express.js API

I am facing a timing issue while working with React.js. My component checks the validity of the user's token and type. If the user is an admin, it should display certain content; otherwise, it should show "you don't have permission". However, I ...

Day Change Triggers React [Native] View Update

I've been working on a React Native component that needs to update itself when the day changes, regardless of user interaction. Is there another method besides using setInterval for this task? If I use setTimeout in my viewDidLoad function with the n ...

Rearrange the array so that any empty values are placed at the end

I am trying to arrange all empty values at the end of an array. The code below demonstrates my attempt: 1) This code moves all empty values to the end of the array, but it does not sort the other values accordingly. var dateArray = [ '',&apos ...

Harnessing the power of Angular JS, Jquery, and Metismenu simultaneously

Is it possible to successfully integrate Jquery, AngularJs, and metisMenu simultaneously? Initially, I added Jquery first, followed by AngularJs and then metisMenu. Unfortunately, metisMenu did not function properly. Subsequently, I rearranged the order, ...

Using vanilla JavaScript in a node.js environment alongside Functional Reactive Programming (FRP) with bacon.js

I am interested in incorporating Functional Reactive Programming (FRP) into my project. I have come across a popular library for node.js called bacon.js that implements FRP. However, I am having trouble finding examples of how to use bacon.js in native J ...

When attempting to access the requested resource in AngularJS, there is no 'Access-Control-Allow-Origin' header present

When attempting to run my web-service from within my code, I encounter the following error message: "XMLHttpRequest cannot load http://mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:/ ...

Looking for assistance on how to automatically close the sidebar or pull navigation menu after clicking on a menu item

My website is designed to be responsive and includes a navigation slider that is hidden off-screen by default. The slider features a vertical push/pull bar that remains visible for users to access the menu. The entire navigation slider is fixed on the page ...

Tips for keeping MUI Autocomplete open even when the input field loses focus

I am currently working with a MUI autocomplete feature that includes a list of items and an edit icon next to each one. The edit icon allows the user to change the name of the option by rerendering it as a textfield. However, I have encountered an issue wh ...

AngularJS is used to vertically collapse three different div elements. This feature

I am facing an issue with the design of my page that contains three panels. Two of these panels have tables, and when viewing the page on a smaller display, it disrupts the layout. I am wondering if there is a way to add collapsible buttons to the panels s ...

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

Tips for sending props to Material UI components

Hey there! I'm currently working on a progressbar component that utilizes animations to animate the progress. I've styled the component using Material UI classes and integrated it into another component where I pass props to customize the progres ...

Clickable div containing a hyperlink

I need assistance with a clickable div that contains a link. Here is the setup: HTML: <div onClick="goToCat(2);" class="author-topics-block "> <a href="http://mywebsite/page/?cat=2">The woman in steel</a> </div> CSS: .author ...

I am having trouble with updating an array in React useState. Every time I try to make changes, it keeps reverting back to the initial state. What could

My current task involves managing a state array called monthlyIncidents, which contains 12 numbers that need to be updated under certain conditions. I attempted to update the elements by copying the array, modifying the specific element, and then updating ...

Creating a one-of-a-kind entry by adding a number in JavaScript

I am looking for a way to automatically add an incrementing number to filenames in my database if the filename already exists. For example, if I try to add a file with the name DOC and it is already present as DOC-1, then the new filename should be DOC-2. ...

Anticipated the presence of a corresponding <div> within the server's HTML nested in another <div>

I've encountered a troubling error on my website while using Next.js. The error is causing layout issues and upon investigation, it seems that the device detection hook is at fault. Here's the hook in question: const isBrowser = typeof window !== ...

Issue encountered while incorporating a PHP file into Javascript code

I'm facing a particular issue where I have a PHP file that is supposed to provide me with a JSON object for display in my HTML file. Everything seems to be working fine as I am receiving an output that resembles a JSON object. Here's the PHP file ...

How can parameters be included in ng-href when using ng-click?

So I have this list of products and I want to pass the current product id when clicking on ng-href by using a function with ng-click in the ng-href. This is what my html file looks like: <div class="agile_top_brands_grids" ng-model="products" ng-repe ...