Using ID attributes to compare JavaScript Objects and generate a distinct list within Angular/JS

I am working with the github API to retrieve an array of objects containing commit data. My goal is to extract a unique list of commitors and format it as shown below to create a graph:

{"id":temp,"label":temp,"type": "number","p": {} }

Here is the code I have written so far:

$scope.git = response.data;
    $scope.o=[];
    angular.forEach($scope.git,function(value){
      var temp = value.commit.author.name;
      if($scope.o.length==0){
        $scope.o.push({"id":temp,"label":temp,"type": "number",
            "p": {}
      })
      }
      else{
      angular.forEach($scope.o,function(ob){
        if(ob.id==temp){
          continue;
        }
        else{
          $scope.o.push({"id":temp,"label":temp,"type": "number",
              "p": {}
        })
      }
      });
}
})

Although this code works, it is not very efficient. Is there a more efficient way to achieve the same result?

Answer №1

To determine if an author is already in the list, you can utilize an object. Here's an example:

$scope.authorList = [];
var authors = {};
angular.forEach($scope.githubUsers, function(user){
    var temp = user.commit.author.name;
    if (authors[temp] === undefined) {
        $scope.authorList.push({"id":temp,"name":temp,"type": "number", "props": {} });
        authors[temp]  = true;
    }
});

Answer №2

When working with JavaScript, utilizing libraries such as underscore or lodash can be beneficial. One particularly useful method to consider is _.uniqBy. For more information on how to use this method, refer to the documentation provided at the following link: https://lodash.com/docs/4.17.4#uniqBy

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

How can you call a function in ExpressJS that is located in a different file?

I am having trouble with my UserController and database configuration file db.js. I am trying to make a function in the UserController access a function in db.js. In my UserController, I have included var db = require('../config/db'); and within ...

The path specified as "react-native/scripts/libraries" does not exist in the file

I've been troubleshooting an error on Github - https://github.com/callstack/react-native-fbads/issues/286. After cloning the repository and running it, I discovered that the error persisted. I am currently updating packages to investigate why this rec ...

The uiGridConstants are mysteriously missing from the global scope, even though they are clearly provided to

Are you struggling to aggregate values from a column in uigrid? I have injected uiGridConstants into the controller, and added ui.grid in my app.js file. Despite my efforts, uiGridConstants is constantly returning as undefined. Any solutions? GridOptions ...

I keep encountering errors with TypeGuard

Looking for some guidance with typescript. Even after implementing a type guard (and including the '?' symbol), I'm still encountering errors in the code snippet below. Is the syntax correct or should I make changes to the tsconfig file? int ...

How can an object inside an array be destructured in just one line?

Consider the following array: const array = [{b:2}] Can you extract the value of b using destructuring in just one line? I attempted something similar to this approach, but it did not yield the desired result: const [{b} = array] ...

ng-click="showInventory()" onClick="currentTemplate='/inventory.html'" Not

I'm facing an issue with my menu list. When I apply the ng-repeat directive, it seems to not work properly. However, when I remove the ng-repeat, everything functions as expected. <div class="reports_header_tabs_holder"> <span ng-repea ...

Anticipated reply should have been in the form of an object, however, it

Encountering an issue with resource.get(): "Error in resource configuration. Expected response to contain an object but got an array". Upon configuring the resource to expect an array, a different error arises: "Error in resource configuration. Expected ...

Can someone assist me in creating a clickable link that opens a menu in HTML when clicked?

I have been attempting for the past few days to open the megamenu by clicking on a link, but despite my efforts, I have not been successful. After reviewing some code, I discovered a clue in the CSS. It seems that setting the visibility value to visible wi ...

Uploading files from AngularJS with ng-flow to Node/Express can be achieved by utilizing empty request bodies

Currently, I am utilizing ng-flow for the purpose of uploading an image. I am facing a challenge where I need to configure my upload to have a content type of application/json. I found some insights on this matter in the following link: Node (Express) req ...

What is the best way to receive a notification when a user chooses any option in a Material UI Autocomplete React component?

My dilemma involves using an autocomplete feature that doesn't behave as expected. I am looking to detect when an option is selected, regardless of whether it's the same as the last selection. The onChange event I'm using only triggers if th ...

Pause the timer once it has reached a specific duration

My challenge involves utilizing a javascript timer that starts at 00:00 and needs to stop at 00:10 (10 seconds duration). The issue at hand is how to continuously monitor the current timer value to appropriately pause it after the designated 10 seconds ha ...

Tips for managing JavaScript within PHP code and vice versa

Usually, I include a lot of JavaScript on the website. However, the client informed me that they were unable to view the website correctly as they had disabled JavaScript on their end. After investigating, I discovered this issue. Now, my dilemma is wh ...

Tips for displaying a gallery of 5 images in a 2-row slider using bxslider

I've been attempting to create a unique image slider using bxslider. My goal is to have a 2-row slider with 5 images displayed in each row. However, I'm encountering difficulties when I try to integrate the HTML, CSS, and JavaScript code. Despit ...

Removing Multiple Object Properties in React: A Step-by-Step Guide

Is there a way in React to remove multiple object properties with just one line of code? I am familiar with the delete command: delete obj.property, but I have multiple object properties that need to be deleted and it would be more convenient to do this i ...

Determining if an event is already associated with a marker in Google Maps API v3

I've set up a marker with a click event listener attached to it. However, I want to check if the click event has already been added to the marker, and if not, add the click event listener. // Add click event listener if it doesn't already exist ...

Unable to access marker windows using markers tag on angular-google-maps

Objective Display various random markers on a map and open an information window upon clicking on them. I attempted to implement this using an example from the API page (markers) and included the necessary code for the window and click handler method. Unfo ...

Step-by-step guide to swapping an element with a textarea element using javascript

My current project involves creating a user profile that includes a text box where users can describe themselves. I've already implemented a separate page for editing the profile, but now I want to add a feature where users can hover over their descri ...

Ways to keep the position of an expanded collapsible table from Material UI intact

I found a collapsible table code snippet on this website: https://mui.com/material-ui/react-table/#collapsible-table However, there seems to be an issue where when I expand a row, the table "grows up" as it increases in size. This behavior is not ideal. I ...

Tips for extracting data from a JSON file

I'm attempting to retrieve a list of music genres from my json file using PHP and JQuery ajax. Here is the format of my json file [ "12-bar blues", "2 tone", "2-step garage", "4-beat", "50s progression", "a cappella", "accordion", " ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...