How to sort an array of multiple objects in AngularJS based on a specific property

Having an array of multiple objects:

{
   "option_12": {
      "id": "0",
      "name": "6 x 330ml",
      "price": "0.00"
   },
   "option_14": {
      "id": 1,
      "name": "12 x 330ml",
      "price": "2.00"
   },
   "option_17": {
      "id": 1,
      "name": "15 x 330ml",
      "price": "4.00"
   },
   "option_10": {
      "id": 1,
      "name": "30 x 330ml",
      "price": "1.00"
   }
}

Using AngularJS Filter orderBy to sort the objects based on price value. Therefore, option_12 should be first and option_10 should be second.

In controller:

$scope.pOptions = $filter('orderBy')($scope.pOptions, 'price');

In the view where select options are populated using ng-options:

<select ng-model="SelectedPOption" ng-options="option.name for option in pOptions|orderBy:'price'"></select>

However, these attempts have not produced any result. https://docs.angularjs.org/api/ng/filter/orderBy

Answer №1

Your code for the select element looks good, but there are some issues with the array it's referencing.

  • Avoid using quotes for keys in JavaScript objects.
  • Make sure the "price" values are numeric for correct sorting.
  • Enclose all elements of the array within square brackets [].
  • Avoid calling the filter function from JavaScript if you're already using it in the markup.

Here is an example:

$scope.pOptions = [{
    id: "0",
    name: "6 x 330ml",
    price: 0.00
}, {
    id: 1,
    name: "12 x 330ml",
    price: 2.00
}, {
    id: 1,
    name: "15 x 330ml",
    price: 4.00
}, {
    id: 1,
    name: "30 x 330ml",
    price: 1.00
}];

For a working example, check this link: https://plnkr.co/edit/n09iupr70zRX56kVrYK9?p=preview

UPDATE: If the data comes in that format from the backend API, you can iterate through the object keys/properties and use the map function to transform the sub-objects into an array:

$scope.pOptions = Object.keys($scope.pOptions).map(function(k) {
   var obj = $scope.pOptions[k];
   obj.price = parseFloat(obj.price);
   return obj;
});

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

Determine the absence of values in a randomly generated array and identify the quantity of missing values

My current challenge involves solving CodeSignal projects, and I recently encountered a problem where a random array of numbers is given, requiring me to determine how many additional numbers are needed to make the array consecutive. For instance, if the ...

The npm lint command is throwing an "Observable `source is deprecated`" error

When I execute the command npm lint on my code, I receive a warning stating "source is deprecated: This is an internal implementation detail, do not use." The specific part of the code causing this issue is shown below: set stream(source: Observable<a ...

As time passes, the Azure Service Bus Consumer experiences a decline in performance

My issue involves managing different topics with subscriptions, each tied to a consumer. Over time, I've noticed a decline in the number of messages received. Despite trying to utilize maxconcurrentcalls, it seems to only be effective at the start. My ...

Difficulty understanding JavaScript sum calculations

I am currently working on a website project. Seeking assistance to enable an increment of one when clicked. Also need guidance on calculating the total price of items collected in a designated section under "number of items selected". Goal is to display ...

How can you establish an environmental variable in node.js and subsequently utilize it in the terminal?

Is there a way to dynamically set an environmental variable within a Node.js file execution? I am looking for something like this: process.env['VARIABLE'] = 'value'; Currently, I am running the JS file in terminal using a module whe ...

What are the steps for generating website endpoints using search query outcomes?

I am currently working on a ReactJS website as a part of my web development bootcamp project. One interesting feature I have incorporated is a search functionality that uses Flask routes to connect ReactJS endpoints (../Language.js) with my Sqlite3 databa ...

Creating texture using an array in three.js

I've been experimenting with generating textures from arrays in threeJS but I'm encountering unexpected results. It seems like the method I'm using to generate the texture is incorrect. When I use the texture from the following link, every ...

Looking for some specific instances of binding attributes within custom AngularJS elements?

I am in the process of developing a custom tag that resembles the following: <mytag type="Big" /> where "type" is an attribute that will be linked to the component and set the text in a label, like so: <label>{{type}}</label> ... (oth ...

How can one authenticate an express session when sending a POST request?

Is there a way to verify that a user is sending a post request in order to prevent unauthorized posting to a URL? I am currently using express-session for this purpose, but I'm open to exploring alternative methods as well. I attempted to implement t ...

Updating Vue 3 asynchronous data doesn't reflect changes when the local settings are modified

I have a dedicated external .js file designed to retrieve data from the backend depending on the website's locale. Check out the code snippet below: import { ref } from "vue"; export function fetchData(section, key) { // Making a GET requ ...

Encountering an issue when implementing a conditional check within the .map() function utilizing ES6 syntax

I'm struggling to assign only the object that contains an iban value to the list in the code snippet below. I haven't been able to fix this issue on my own and would appreciate some assistance. This.ibanList = this.data.map( (value, in ...

The Angular event handler fails to trigger change detection upon clicking

I am facing a simple problem where I have an element in a component's template with an ngIf condition and a (click) handler. Initially, the element is not rendered because the ngIf condition evaluates to false. What makes this interesting is that an ...

Making a Jquery 1.10.2 cross-domain request

I am in need of assistance with the following code snippet: function doPoolPartyGetChildrenAjaxRequest(parent) { return $.ajax({ url: "http://127.0.0.1:8086/PoolParty/api/thesaurus/1DCE2E49-7DD8-0001-524C-1A1B14A0141A/childconcepts", data: {lan ...

Suggestions for improving the smoothness of the Bootstrap toggle hide/show feature

Recently completed my bootstrap toggle hide/show feature and everything seems to be functioning correctly, except for the transition between the different contents. The borders appear jagged and not smooth when activating the toggle. I suspect there may b ...

`How can I effectively manage errors within an ASP.NET HTTP handler?`

I wrote an Httphandler in asp.net that is responsible for returning a file. Within the code, I have implemented Response.AddHeader("Content-Disposition", "attachment; filename=somefile.ext"); to ensure that the page URL remains unchanged. However, when an ...

Creating a repository of essential functions in AngularJSDiscover the steps to set up a

I am looking to create a set of reusable functions in AngularJS for CRUD operations that can be used across multiple entities in my project. I have already set up a factory using $resource for server communication, which looks like this: Model File: var ...

Error encountered: "Jest error - TypeError: Unable to access property 'preventDefault' because it is undefined."

I encountered an issue while testing the function below, resulting in the error mentioned above. function toggleRecovery = e => { e.preventDefault() this.setState( { recovery: !this.state.recovery }, () => { ...

utilizing a message collector for configuring embed fields

I'm currently working on a message collector feature that collects data to use in an embed's title, description, and color. My goal is to have each value correspond to a different aspect of the embed. However, I've encountered some challenge ...

Recursively toggle child elements using JQuery

My knowledge of JQuery is limited, so here's the issue I'm facing. Below is an example of the HTML structure: <ul class="first-class"> <li class="second-class"> <a href="#_"> <i class="fa fa-plus"></i& ...

Press a button to link a click event handler to another button

function example() {console.log('example');} $('#button1').click(function(){ $('#button2').onclick = example(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ...