Filter an array of objects to only include the unique values and remove any duplicates

var  Error-dictionary = [
   {
      code:599,
      MSG:'unknown'
   },
   {
      code:404, 
      MSG:'not found'
   },
   {
      code:599, 
      MSG:'unknown'
   }
]

I would like to transform the data structure into something similar to:

[
  {
     code : 599,
     count:2,  
     MSG : 'unknown', 
     code :404,
     count:1,
     MSG : 'not found' 
  }
] 

and then add it to $scope.alerts as a message.

The error codes and messages can vary dynamically.

Answer №1

If you need to retrieve the occurrences of a specific property within an array of objects, look no further than underscore.js. It's a simple and effective solution!

<script src="http://underscorejs.org/underscore-min.js"></script>
<script>
  window.onload = function () {
    var propertyArray = [
      {id: 123, category: 'fruit' },
      {id: 456, category: 'vegetable'},
      {id: 123, category: 'fruit'}
    ];

    var result = _.groupBy(propertyArray, function (obj) {
      return obj.id;
    });

    var newArray = []; 

    for(var key in result) {

        var id = key; 
        var values = result[key]; 
        var category = values[0].category; 
        var quantity = values.length; 
        newArray.push({ id : id, category: category, quantity: quantity }); 

    }; 

    console.log(newArray); 
  };
</script>

Answer №2

To solve the problem, first create a temporary object using the error code and message as keys. Then, iterate through the data array and populate the temp object with unique key-value pairs. Finally, push each item from the temp object into an output array.

var tempObj = {}, resultArr = [];
data.forEach(function (item) {
    var tempKey = item.code + item.MSG;
    if (!tempObj.hasOwnProperty(tempKey)) {
        tempObj[tempKey] = angular.copy(item);
        tempObj[tempKey].count = 0;
    }
    tempObj[tempKey].count++;
});

for(var key in tempObj) {
   resultArr.push(tempObj[key]); 
}
$scope.errors = resultArr;
console.log($scope.errors);

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

Dealing with query strings within routeprovider or exploring alternative solutions

Dealing with query strings such as (index.php?comment=hello) in routeprovider configuration in angularjs can be achieved by following the example below: Example: angular.module('app', ['ngRoute']) .config(function($routeProvider, $loc ...

What is a way to activate the onSelectionChange event only when the cursor moves without any changes in the input?

In my React Native app, I have a use case where I want to implement mentions. This requires calling a function on the onSelectionChange event only when the text in the input remains unchanged but the caret position has moved. Currently, the onSelectionCha ...

Conceal the parent element if there are no elements present within the child element

Look at the markup provided: <div class="careersIntegration__listing" id="careers-listing"> <div class="careersIntegration__accordion"> <div class="careersIntegration__accordion-header"> <span class="careersIntegrat ...

Implement the callback-console.log feature from the epic-games-api into an Express.js application

Looking to integrate Epic Games output into an Express.js GET request but don't have any JavaScript experience, so go easy on me! XD const EpicGamesAPI = require('epicgames-status'); const express = require('express') const app = ...

What is the most effective method for transferring and accessing data within a child form component?

This is how I am currently handling it: Parent.vue: // Template <form-child :schema="schema"><form-child> // JS data () { return { schema: [{ // name: '', value: '', type: '' }, { //etc ... }] } } For ...

Is it possible to eliminate the default placeholder text from Safari browser?

My goal is to design a form that includes date and time input fields. The placeholder text should move up by X pixels when the user clicks on the field. While the form appears fine in Chrome, there seems to be an issue with overlapping form fields in Safa ...

Is it possible to create a sticky element that stays fixed to the window without using JavaScript?

Using position: sticky has been a game-changer for me. It resolves many issues without the need for JavaScript. However, I've encountered a roadblock. I am trying to create a sticky element that is nested inside multiple <div> elements. Since po ...

What are the steps to integrate jQuery into an Angular 8 application?

I am currently working on an application that relies on SignalR for communication with a desktop application. In order to make use of SignalR, I include jQuery in my .ts file. However, after migrating from Angular 7 to Angular 8, it appears that this setup ...

the least amount of steps required to organize a list

Currently, I am working on a problem from Codeforces that involves sorting an array by either moving the elements to the beginning or the end of the array. Initially, I thought it was related to finding the longest increasing subsequence, but that approa ...

Deploying a static website using Node.JS without relying on any frameworks

I am currently working on deploying static web pages, which include HTML, CSS, and JS files, onto Node.js without utilizing any frameworks such as Express. I started by placing all the necessary webpage files into a public folder and then called the index. ...

Connecting a JavaScript variable

Is it possible to include a JavaScript variable in a link? I've tried the code below but it just shows a blank page. The viewData.php file will contain PHP GET Variables used to retrieve data based on the period and type, which determine whether renta ...

Loading of iframes occurs only after receiving the content sent through the postMessage function

I have a scenario where an iframe is used to receive information through the contentWindow.postMessage function in order to log in to a page that I am creating. However, I am facing an issue where the page loads before the contentWindow.postMessage message ...

When I click on the delete button in the dialog box, a horizontal scroll bar appears on the page

I'm dealing with a table that includes an 'approved' column with three conditions. One of these conditions triggers the appearance of a delete button along with a confirmation dialog box made using Vuetify's dialog component. The iss ...

Guide on executing a Python script using Node.js

I have set up a node.js server on Raspberry Pi and encountered an issue when trying to run a python script from it. Despite receiving the correct output from the client, the file fails to execute in this instance involving socket.io. The socket functiona ...

Is a DOM lookup performed each time Vue's ref is utilized?

Exploring the capabilities of Vue.js, I have integrated a few refs into my current project. However, I am curious about the efficiency of calling refs in methods. Does Vue perform a DOM lookup every time a ref is called, or does it store all refs once for ...

Changing array indices in JavaScript by splicing elements

I'm experiencing a curious issue that seems to involve overwriting array indices after splicing, or at least that's what I suspect. This problem arises in a small game project built using phaser 2 - essentially, it's a multiplayer jumping ga ...

How can AngularJS utilize variables from an external JavaScript <script> file within an HTML document?

As someone unfamiliar with AngularJS, I have a simple inquiry regarding the subject. The code on my page begins by defining an app and controller: <script> var isisApp = angular.module('isisApp', []); isisApp.controller('Acco ...

Sinon - observing the constructor function

While I've come across a few related inquiries, none seem to address what I am specifically looking to achieve. My goal is to monitor a constructor method in such a way that when an object created with the constructor calls this method from a differe ...

What factors might cause varying WebGL extension availability?

When I analyze my code, I am checking for available WebGL extensions. console.log(GL.getSupportedExtensions()); This results in an array containing 9 extensions. https://i.sstatic.net/5sTcX.png However, upon inspecting my extensions on a platform like ...

UI-Router - templateUrl: "Ensure the content is securely delivered via HTTPS"

I am currently using HTTPS for my website. I have a requirement to send a request for templateUrl, not to a static file, but to the router: /:lang/content/library/book/:bookId Below is the setup for my state: .state('book', { url: '/ ...