AngularJS: ng-repeat excluding duplicate keys

Here is a collection of objects I am working with:

[{
 key:test1
 name: name1
},
{
 key:test1
 name: name2
},
{
 key:test2
 name: name3
}]

I am currently using ng-repeat to showcase them:

<tr ng-repeat=item in list>
  <td>{{item.key}}</td>
  <td>{{item.name}}</td>
</tr>

I am wondering if there is a way to merge values with the same keys without altering the structure, so that test1 is not repeated twice like in my example.

Current output:

test1 : name1

test1 : name2

test2 : name3


Desired output:

test1 : name1

_____  name2

test2 : name3

Answer №1

If you're looking to group items, consider using the groupBy filter:

angular.module('app', ['angular.filter']).controller('ctrl', function($scope){
  $scope.list = [{
     key:'test1',
     name: 'name1'
    }, {
     key:'test1',
     name: 'name2'
    },{
     key:'test1',
     name: 'name3'
    },{
     key:'test2',
     name: 'name4'
    }];
})
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.16/angular-filter.js"></script>

<table ng-app='app' ng-controller='ctrl'>
  <tbody>
    <tr ng-repeat-start="(key, value) in list | groupBy: 'key'">      
      <td>{{key}}</td>
      <td>{{value[0].name}}</td>
    </tr>
    <tr ng-repeat-end ng-repeat='item in value.splice(1)'>
      <td></td>
      <td>{{item.name}}</td>
    </tr>
  </tbody>
</table>

Answer №2

ng-repeat="element in items | distinct:'identifier'"

Answer №3

Follow these steps to consolidate the common key values in one place using angular-filter:

angular.module('app',['angular.filter']).controller('mainCtrl', function($scope){$scope.list = [{
       key:'test1',
       name: 'name1'
      },
      {
       key:'test1',
       name: 'name2'
      },
      {
       key:'test2',
       name: 'name3'
      }]
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.16/angular-filter.min.js"></script>


<div ng-app='app' ng-controller='mainCtrl'>
    <div ng-repeat="(key, value) in list | groupBy: 'key'">
      <span ng-repeat='val in value'>{{val.name}} </span>
    </div>     
</div>

Answer №4

Ensure the list is updated before utilizing ng-repeat.


function updateList(obj, key, value) {
   var newList = [];
   var lookup = {};

   for(var index in obj) {
      if (lookup.hasOwnProperty(obj[index][key])) {
         obj[index][value] =  lookup[obj[index][key]][value] + " " + obj[index][key];
         lookup[obj[index][key]] = obj[index];
      } else {
         lookup[obj[index][key]] = obj[index];
      }
   }

   for(index in lookup) {
      newList.push(lookup[index]);
   }
   return newList;
}

var updatedList = updateList(array, "key", "name");

Answer №5

If you're looking for a solution, consider the following example:

var app = angular.module('myApp', ['angular.filter']);
app.controller('myCtrl', function($scope) {
    $scope.items = [{
     "key":"test1",
     "name": "name1"
    },
    {
     "key":"test1",
     "name": "name2"
    },
    {
     "key":"test2",
     "name": "name3"
    }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.16/angular-filter.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
    <div ng-repeat="item in items | groupBy: 'key'">
    <h3>Key : {{item[0].key}}</h3>
      <p>Names : <span ng-repeat='i in item'>{{i.name}} </span></p>
    </div> 
</div>

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

Reduce the length of the text to 50 characters after the current word, while ensuring that the word

Looking for a way to shorten text after reaching 50 characters, making sure not to split words in the middle when cutting off. For example: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars) Desired output: Contrary to popular belief, ...

What is the method for setting and comparing collectionsjs equality?

I'm interested in utilizing the data structure. Within the factory method, you have the opportunity to specify equals and compare parameters: SortedMap(entries, equals, compare). Can anyone provide insight into what the expected formats for these pa ...

How can I retrieve the value of a div nested within another div?

Alright, let's talk about a situation where we have a draggable HTML div element: <div id="server" draggable="true" ondragstart="return dragStart(event)">Server</div> and also a target div: <div id="target1" ondragenter="return dragE ...

struggling to determine the connection status between tables (Many-to-many or one-to-one)

Seeking assistance: I am working with two tables (member, event) where each member attends multiple events and each event has multiple attendees. Do these relationships represent a many-to-many or one-to-one relationship? ...

Can you explain the reference point used in the `drawImage()` function on a canvas?

Here is an inquiry concerning the usage of the drawImage() function. var x = (i-j)*(img[0].height/2) + (ctx.canvas.width/2)-(img[0].width/2); var y = (i+j)*(img[0].height/4); abposx = x + offset_x; abposy = y + offset_y; ctx.drawImage ...

What is the best way to integrate nano.uuid into a series of promises that are fetching data from the database?

When working with express routing and nano, I encountered a challenge: router.get('/', function (request, response) { db.view('designdoc', 'bydate', { 'descending': true }) .then(results => { // data ...

Identifying Mistakes during Promise Initialization

Looking for a more efficient way to work with Bluebird promises Promise.resolve() .then(function() {return new MyObject(data)}) .then.....etc .catch(function (e){ //handle it}) I am dealing with MyObject and data coming from an external sourc ...

Is it feasible to incorporate a third-party JavaScript file into a React application?

I have a JavaScript file from a previous MVC project that generates a basic table using ExtJS. Currently, I'm working on developing a new React application with a navigation bar and sidebar. My goal is to explore the possibility of importing the exis ...

Unlocking Discord Account Information through OAuth2

Currently, I am in the process of developing a moderation bot for Discord. I am working on implementing a paid plan and as part of that, I require users to log in with their Discord account using OAuth2. This allows me to retrieve user data and identify wh ...

RectAreaLight in Three js does not produce any light reflection when used with MeshPhongMaterial due to lack of support for OES_texture_half

After trying to incorporate a RectAreaLight into my three.js scene where I have objects with MeshPhongMaterial, I noticed that there is no light reflection on the objects. A useful example can be found here: Link If you open the developer tools, you can s ...

Running Handlebars using NodeJS can sometimes result in a "Cannot find module './parser'" error

After successfully creating and implementing a Handlebars template in the Browser, my next goal is to utilize the Handlebars precompiler, which requires a NodeJS module. I have already downloaded Handlebars for NodeJS along with all dependencies locally (n ...

Table of contents not working on Vercel, yet functions properly on localhost

I'm struggling to incorporate a dynamic table of contents into my blog page on next.js. The code functions perfectly on my local server, but upon deploying it to Vercel, I encounter the following error: TypeError: Cannot read properties of undefined ( ...

What is the best way to manage sessions in angularjs using javascript?

Only at two specific instances in the application should the login prompt be displayed: When trying to access a page that requires login while not logged in, such as my profile page. When attempting an action that necessitates ...

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

Create a function in JavaScript that generates all possible unique permutations of a given string, with a special consideration

When given a string such as "this is a search with spaces", the goal is to generate all permutations of that string where the spaces are substituted with dashes. The desired output would look like: ["this-is-a-search-with-spaces"] ["this ...

Encountering Uncaught Syntax Error when attempting a request with JSON parameters

Currently, I am using Fetch to send a post request to my server while including some additional information. Here's the code snippet: var rating = document.getElementById("rating"); var ratingValue = rating.innerHTML; fetch("/films",{ method: "po ...

Error: JSON parsing error encountered due to an unexpected token 'U' while trying to read a file with

Currently, I am utilizing Node.js version 12.14.1 and encountering a problem while attempting to parse a JSON file that includes the \U0001f970 character. The file's content that needs to be read and parsed is as follows: {"randomKey": ...

Receiving a "Bad Request" error when trying to access a website

Every time I attempt to call a lengthy URL, I encounter a Bad Request issue. https://localhost:44320/RespostaEmail/96635/750396/[%7B%22IdItem%22:8,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:1,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:3,%22IdTipoReposta%22:8 ...

A more organized method for assigning Enter key presses

function onLoad() { eworkData.FieldByName('SearchReference').HTMLfield.onkeydown=function(evt) { var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode; if( keyCode == 13 ) { eworkDat ...

Failure to send Websocket connection

Currently working on PHP, here's a snippet: $room_array = array(); $room_array[0] = 'room-list'; $room_array['info'] = array('room_name' => $room['room_name'], 'owner' => $username['usernam ...