Sorting JSON object lists by the ID column in AngularJS is an efficient way to organize

Before rendering in the browser, I need to organize my JSON data object. Here is the format of my JSON:

$scope.cityData= [
    {
        id: '520',
        city:'col01'
    },
    {
        id: '410',
        city:'col02'
    },
    {
        id: '412',
       city:'col03'
    }]

I attempted to sort it using code, but there seems to be an issue as the console log did not show it as sorted.

$scope.cityData.sort(function (a, b) { return a.id - b.id });
console.log($scope.cityData); 
$scope.newCitySort = $scope.cityData;

I also want to assign this sorted data to a new scope variable. How can I achieve this?

Answer №1

If you find that there's no requirement for the $scope.cityData to be sorted, you have the option of utilizing the orderBy filter

Here is how it can be implemented in your html:

<ul ng-repeat="city in cityData | orderBy: 'id' ">
  <li>**insert your list rendering code here**</li>
</ul>

This will result in your collections being displayed in order based on their id values.

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

Populate a database with information collected from a dynamic form submission

I recently created a dynamic form where users can add multiple fields as needed. However, I'm facing a challenge when it comes to saving this data into the database. You can view a similar code snippet for my form here. <form id="addFields" me ...

Prevent alert box from closing automatically without clicking the ok button in ASP.NET

I'm creating a project in ASP.NET where I need to display an alert box and then redirect to another page. Below is my code: var s = Convert.ToInt32(Session["id"].ToString()); var q = (from p in db.students where p.userid == s ...

What is the best way to show a message on a webpage after a user inputs a value into a textbox using

I have a JSFiddle with some code. There is a textbox in a table and I want to check if the user inserts 3000, then display a message saying "Yes, you are correct." Here is my jQuery code: $("#text10").keyup(function(){ $("#text10").blur(); ...

Tips for transitioning to TypeScript: Splitting lengthy Revealing Module Patterns into smaller parts

We are in the process of converting some JS code to TypeScript. Our JavaScript files are currently written using Revealing Module Patterns. Here is a simplified version of the pattern: var thing = (function() { var var1, var2; function init() { ...

Retrieve the value of a JavaScript variable

Currently, I am working on developing a web application that utilizes the Google Maps Direction API. Within a variable named summaryPanel.innerHTML, I store essential details about addresses and distances. I need to utilize the distance data for additional ...

Error with image loading event - inability to load custom image from user-provided URL or input - load() function malfunctioning

Is there a way to trigger a simple event (such as changing HTML in span) when an image from a custom or user-defined URL finishes loading? You can find an example of what I'm trying to achieve in this JSFiddle link. $('#btn').click(functio ...

Issues with retrieving the subsequent anchor element using Jquery Slider

(Apologies for the lengthy post. I like to provide detailed explanations.) Just starting out with Jquery, trying my hand at creating a custom image slider from scratch. Got the slider working with fade effects using this code: Javascript: $(document).re ...

Changing AngularJS API requests from PHP to JSON format

Hey there, I have an app that is capable of connecting to an API. However, it currently can only get API requests from a PHP file. I am looking to modify the code so that it can accept .json API files instead. Factory factory.readProducts = function(){ ...

Chrome browser is experiencing an issue with the Modal RadWindow not closing properly

In my main "Report" page, there are actions available to the user that open a modal RadWindow. The user can then take actions within the modal window, click Save, and the modal window should close while the main grid refreshes. While this functionality wo ...

Creating a dependent picklist feature using node.js and express

I am currently delving into the world of node.js and express. In my node.js application, I am utilizing express along with express-handlebars as the templating framework. My goal is to incorporate a dependent picklist that dynamically renders based on the ...

How can we combine refs in React to work together?

Let's consider this scenario: I need a user to pass a ref to a component, but I also have to access that same ref internally. import React, { useRef, forwardRef } from 'react'; import useId from 'hooks/useId'; interface Props ext ...

Unable to display Polygon using ReactNativeMaps

Having trouble displaying the polygon correctly on my screen. I suspect it's due to receiving an array of objects from my API. This is the code snippet in question: <MapView.Polygon coordinates={poligonofinale} strokeColor="#000" fillColor= ...

How can I deselect the 'select-all' checkbox when any of the child checkboxes are unchecked?

Here is the code provided where clicking on the select-all checkbox will check or uncheck all child checkboxes. If any child checkbox is deselected, the 'select-all' checkbox should also be unchecked. How can this be achieved? $(document).read ...

Upon updating my application from Angular 14 to 16, I encountered an overwhelming number of errors within the npm packages I had incorporated

After upgrading my angular application from v14 to v16, I encountered numerous peer dependencies issues, which led me to use the --force flag for the upgrade process. However, upon compiling, I am now faced with a multitude of errors as depicted in the scr ...

When Google Chrome encounters two variables or functions with the same name, how does it respond?

I am curious what happens when Google Chrome encounters two variables with the same name. In my particular case, this issue arises in the code snippet available at this link, which is a small portion of the entire code. I am facing an issue where placing C ...

How can I implement jQuery autocomplete with customized settings?

In my Drupal project, I am looking to implement jQuery's auto complete feature to search for nodes based on their titles. I am having trouble finding examples that align with my specific requirements: The URL structure should be: /api/node/title/{wh ...

How can we alert users when data has been updated without the need for a page

The following code was authored by me: $('.actionButton').click(function(){ var buttonValue = $(this).val(); var userId = '<?php echo $_SESSION['id']; ?>'; console.log(userId); ...

What are the ideal strategies for handling asynchronous calls in Vuex?

Currently, I am exploring Vuex and have come across the concepts of using Actions instead of Mutations when dealing with asynchronous code. I find myself pondering whether it is more beneficial to handle all the asynchronous logic within the action itself ...

Issues have been reported with event listeners (specifically onkeypress and onkeydown) not functioning properly on Android's numeric keyboard

After countless hours of troubleshooting, I am convinced that something is awry. My issue revolves around a simple input field: <input type="number"> I intend for it to exclusively accept numbers (0-9) and nothing else. To accomplish this, I i ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...