How to effectively filter arrays using Angular.js

One array of objects that I have on hand looks like this:

var arr = [{id:1, name: 'frank', type: 'great'}, {id:2, name: 'john', type: 'good'}, {id:3, name: 'mark', type: 'great'}, {id:4, name: 'mary', type: 'bad'}];

Sometimes, I find myself needing to display 3 different html elements. Each element should contain a list of names with the same "type".

I could run 3 separate loops to search for these names, but I'm wondering if there's a more efficient method. The best approach I've thought of is to "filter" the array for each iteration. Even though I would still loop 3 times, it might be a more targeted way to go through only the elements that matter.

I'm unsure about how to go about filtering this data. I'm using angular.js currently, but I'm open to using plain JavaScript as well. Is there a better solution out there?

*****EDIT*****

Special thanks to duffy for suggesting the filter function. Here's my dilemma:

Within an .html file, there's a div structured like this:

<div ng-repeat="person in peopleContainer.get_people()">

The peopleContainer is defined as a factory in services.js. This factory holds the array of individuals and functions for adding new people or retrieving the entire list.

Currently, the ng-repeat directive above doesn't seem to be functioning properly. When a new person is added, it reflects in the array, but no changes are seen in the div container. The ng-repeat isn't triggering at all. Could this issue be due to the location of the people array within the service.js file? If so, is there a workaround for this situation?

Answer №1

According to @duffy356, the solution is to utilize filters.

Edit Make sure to fulfill your promise within the controller :) (updated snippet with promise resolution)

var app = angular.module('my-app', []);

app.controller('MainCtrl', function($scope, $q, $timeout) {
  $scope.arr = [];
  
  $scope.get_people = function(){
    var results = [{id:1, name: 'frank', type: 'great'}, {id:2, name: 'john', type: 'good'}, {id:3, name: 'mark', type: 'great'}, {id:4, name: 'mary', type: 'bad'}];
    var deferred = $q.defer();
    $timeout(function () { deferred.resolve(results); }, Math.random() * 1000, false);
    return deferred.promise;
  }
  
  $scope.get_people().then(function(result) { $scope.arr = result;});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="my-app" ng-controller="MainCtrl">
  <div ng-repeat="a in arr track by $index">
    {{ a.name }} {{ a.type }}
    <div style="margin:10px" ng-repeat="aa in arr | filter : { type: a.type } track by $index">
      {{ aa.name }} <b>{{ aa.type }}</b>
    </div>
  </div>
</body>

Answer №2

Avoid calling peopleContainer.get_people() within the ng-repeat directive. Instead, retrieve the data in the controller and store it in a scoped variable. Then, use this variable in the ng-repeat.

Controller:

$scope.people = peopleContainer.get_people();

HTML:

<div ng-repeat="person in people">

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

What is the best way to showcase a table below a form containing multiple inputs using JavaScript?

Context: The form I have contains various input fields. Upon pressing the [verify] button, only the "first name" is displayed. My goal is to display all input fields, whether empty or filled, in a table format similar to that of the form. Exploration: ...

I am facing a challenge with AngularJS where I am unable to navigate between pages using the

I'm having issues with my route file app.js. Whenever I click on any link or button, it redirects me to books.html. What could be the mistake I'm making? var myApp = angular.module('myApp', ['ngRoute']); myApp.config([&apo ...

Revise if a specific file is not being called by AJAX

I am currently utilizing a routing library known as Grapnel.js. It requires URLs in the format of index.php#something/something, which is why I am using htaccess to rewrite /something/something to match that structure. However, I would like the flexibility ...

Error: Unexpected character encountered

When attempting to parse an array of objects enclosed in double quotes, I encountered an error: Uncaught SyntaxError: Unexpected token ' var test = "[{'key' :'D', 'value': 'Deceased Date'},{'key' ...

The functionality of displaying odd and even numbers is not functioning properly when using ng-hide to separate data between two tables

I am facing an issue with multiple tables that display data fetched from a JSON source. The data is separated into two tables based on certain criteria, causing the index to become incorrect. As a result, AngularJS is unable to determine which rows shoul ...

Show two choices in a select box next to each other

I've been attempting to display a select box with two options side by side in a list format. Struggling to find any libraries that can achieve this functionality. Here is an example: <select> <option x><option y> <optio ...

Tips for customizing the IconButton appearance in material-ui

While Material-ui offers a default icon button, I am interested in customizing its design to resemble this: IconButton design needed Could you please advise me on how to make this change? Thank you. ...

Transferring data between two screens within an Ionic app by harnessing the power of angularJS

As a beginner in Ionic and Angular development, I am currently facing an issue with my Ionic application. I have two pages - one with drop-down selects and a submit button, and another page to process the user's choices and display the results. The pr ...

Issue involving retrieving keys from multiple classes in a JSON object

I am facing some difficulties with JSON and JavaScript as I am a beginner in this area. Currently, I am attempting to iterate through all the keys["name"] of this JSON data. var l = [{ "pages": [ { "name": "Scan", "elements": [ { "type": ...

How to prevent writing to the z-buffer for a specific object in Three.js

I have been attempting to prevent a write to the z-buffer for a specific object in three.js. This is what my code currently looks like: mesh.onBeforeRender = function(renderer){renderer.context.depthMask(false)}; mesh.onAfterRender = function(renderer){r ...

Delivering variables beyond ng-view boundary

I have an HTML page located at /profile#IDGoesHere that is connected to an ng-app. The ng-app contains three columns (using Bootstrap) and the middle column utilizes Angular's ng-view. The structure looks like this: /profile#IDGoesHere (and within i ...

What is the best way to calculate the frequency of a specific word in an array?

I have been attempting to eliminate duplicates from my array and determine the frequency of each word appearing in the array. While I have come across methods to address this issue, none of them seem to be working. For instance, when I input the text "this ...

jQuery custom slider with advanced previous and next navigation capability for jumping multiple steps

I am currently learning jQuery and programming in general. Instead of using a pre-built plug-in, I decided to create my own image slider/cycle from scratch to keep the code concise and improve my skills. My function goes through each li item, adding a &ap ...

Confirm the email during registration with Node.js and Express.js

Hello, I am just starting out with the MeanJS framework (MongoDB, ExpressJS, NodeJS, and AngularJS) and I could really use some guidance on how to send an email with a verification link for new users. Can you please help me understand this process? ...

Is it possible to alter the location of a button through a click event

On the left side of the container, there is a button with the text "Go Right!". When clicked in this position, the button moves to the right side of the container. When the button is on the right side, the text changes to "Go Left!" and clicking it will m ...

Exploring the orderBy feature in the react-firebase-hooks library with NextJS

Recently, I've been utilizing the React Firebase Hooks package from this GitHub repository. The code snippet below has been functioning smoothly for me. const [posts, loading, error] = useCollection( firebase .firestore() .collection(& ...

Rounding off numbers with decimal points

I am dealing with product prices and have the following numbers: <span class="amount">77.08</span> <span class="amount">18.18</span> <span class="amount">20.25</span> My goal is to always round them up, regardless of t ...

What is the process for converting an array of integers into a byte stream and sending it to the client using Node.js?

How can I convert an array of integers into a bytestream and send it to the client using Nodejs? Let's say I have the array [17, 256, 82]. I am setting the content-type as application/octet-stream. My goal is to send a response with the binary stre ...

Retrieve webpage using HTML stored in web storage

I am exploring a new idea for an application that utilizes local storage, and I am seeking guidance on the most effective way to load content after it has been stored. The basic concept of the app involves pre-fetching content, storing it locally, and the ...

jQuery removes HTML tags from XML documents

I currently have a setup where a page is functioning as an AJAX loader with the help of jQuery. It is designed to retrieve XML documents, like the one shown below, and then place the values of title, authPhrase, and content into the appropriate div element ...