Nid Help guys!

There is an array

$scope.contacts = [ { "id": "1", "name": "first name", "surname": "first surname", "age": "29", "group": "group 1", "description": "This is first", "note": "some notification" }, { "id": "2", "name": "second name", "surname": "second surname", "age": "27", "group": "group 2", "description": "This is first", "note": "some notification" }, { "id": "3", "name": "third name", "surname": "third surname", "age": "25", "group": "group 1", "description": "This is first user", "note": "some notification" }] 

The thing is done on Angular. In one tab, you need to display a list of all users (there are no problems with this). In the second - the name of the groups and its members. Tell me, please, how to filter by groups!

I get a list of groups that exist:

 $scope.selectGroups = new Set(); $scope.groups = []; var test = []; for (var i = 0; i < $scope.contacts.length; i++) { $scope.selectGroups.add($scope.contacts[i].group); } test = JSON.stringify(Array.from($scope.selectGroups)); $scope.groups = JSON.parse(test); 

Beginner and I understand that I do not know much. I hope for help!

  • What are you doing JSON.stringify and immediately JSON.parse? - Arnial
  • Do you need to sort by key value (task in title) or filter by group (task description in text)? - Arnial
  • I tried to display the resulting list of groups from test, Angular did not want to output. After JSON operations, it worked. - Slava PV
  • On the page you need to display the name of the group and its members. Groups can be added. I understand that I need an array with the keys "group names", select the list of users by group and get an array of contacts for each key. Perhaps I climb into the wilds (( - Slava PV
  • stringify and parse are not needed; Array.from is sufficient. - Arnial

2 answers 2

You can filter by the filter function

 $scope.contacts.filter( contact => contact.group === 'group 1' ) //оставит кантакты только из группы 1 

You can sort the sort function

 $scope.contacts.sort( (contact1, contact2) => contact.group.localeCompare( contact2.group ) ) //отсортирует контакты по группе. 
  • is there definitely not a comma? ..contact => contact.group .. - Kirill Korushkin
  • @Kirill Korushkin function there, you can check in the browser. - Arnial

Redid a bit and earned!

  $scope.groups = {}; $scope.selectGroups = new Map(); for (var i = 0; i < $scope.contacts.length; i++) { if (!$scope.selectGroups.has($scope.contacts[i].group)) { var users = []; $scope.selectGroups.set($scope.contacts[i].group, users); $scope.selectGroups.get($scope.contacts[i].group).push($scope.contacts[i].name); } else { $scope.selectGroups.get($scope.contacts[i].group).push($scope.contacts[i].name); } } $scope.groups = Array.from($scope.selectGroups); 

On the page I display the following:

 <div ng-repeat="group in groups"> {{group[0]}}<br> <div ng-repeat="gr in group[1]"> {{gr}} </div> </div> 

As a result, I get the name of groups and its members called.

Thank!