Sorting objects in AngularJS

Within the primary Array Object, my JSON data looks like this

obj = [{{"title":"1-Introduction"},
       {"title":"5-Introduction"},
       {"title":"20-Introduction"},
       {"title":"4-Introduction"} }]

I am looking to sort the above object as follows

obj = [{{"title":"1-Introduction"},
       {"title":"4-Introduction"},
       {"title":"5-Introduction"},
       {"title":"20-Introduction"} }]

This is what I have attempted so far

$scope.checkWeightage=function(){
            thisObj.scheduleSubject.map(itm=>itm.sectionRange.map(subItm=>{
                    var min = subItm.chapterActualWeightage-(subItm.chapterActualWeightage/10);
                    var max = subItm.chapterActualWeightage+(subItm.chapterActualWeightage/10);
                    var sum = subItm.items.reduce((total,it)=>{
                       return total+it.actualWeightage;
                    },0);
                    subItm['weightageError'] = (sum>max || sum<min)?true:false;
                    subItm['ChapterActualWeightageCurrently'] = parseFloat(Math.round(sum*100)/100);
                    subItm.items.sort((a,b)=>a.title.split(/_(.+)/)[0]>b.title.split(/_(.+)/)[0]);
                })
            ); console.log(thisObj.scheduleSubject[0].chapterData); //.1[0].title);
            //console.log("CHECK weightage",thisObj.scheduleSubject);
        }

How can I track the title in my main Array?

alert(thisObj.scheduleSubject[0].sectionRange[0].items[0].title);

I aim to arrange all items based on the digits in their titles before the '-' character, for example 1-, 2-, 3-, 4-, 5-, 6-, 21-, 56-, and so on.

Main Array Structure

[
  {
    "id": "25",
    "section": "1",
    "sectionRange": [
      {
        "sectionNumber": 1,
        "effectAllowed": "all",
        "Date": "",
        "items": [
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 283,
            "actualWeightage": 3.42,
            "totalPaperMarks": 132,
            "title": "10-Creation & Registration of Charges",
            "$$hashKey": "object:146"
          },
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 284,
            "actualWeightage": 2.23,
            "totalPaperMarks": 132,
            "title": "11-Allotment of Securities & Issue of Certificates",
            "$$hashKey": "object:147"
          },
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 285,
            "actualWeightage": 1.37,
            "totalPaperMarks": 132,
            "title": "12-Membership in a Company",
            "$$hashKey": "object:148"
          },
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 286,
            "actualWeightage": 3.42,
            "totalPaperMarks": 132,
            "title": "13-Transfer & Transmission of Securities",
            "$$hashKey": "object:149"
          },
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 287,
            "actualWeightage": 7.53,
            "totalPaperMarks": 132,
            "title": "14-Institution of Directors",
            "$$hashKey": "object:150"
          },
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 288,
            "actualWeightage": 1.37,
            "totalPaperMarks": 132,
            "title": "15-Independent Directors",
            "$$hashKey": "object:151"
          },
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 289,
            "actualWeightage": 13.35,
            "totalPaperMarks": 132,
            "title": "16-Board & its Powers",
            "$$hashKey": "object:152"
          },
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 290,
            "actualWeightage": 8.22,
            "totalPaperMarks": 132,
            "title": "17-Appointment & Remuneration of Key Managerial Personnel",
            "$$hashKey": "object:153"
          },
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 291,
            "actualWeightage": 6.68,
            "totalPaperMarks": 132,
            "title": "18-General Meetings",
            "$$hashKey": "object:154"
          },
          {
            "subjectId": 25,
            "section": 1,
            "chapterId": 292,
            "actualWeightage": 1.37,
            "totalPaperMarks": 132,
            "title": "19-Loans & Investments by Companies",
            "$$hashKey": "object:155"
          }

Answer №1

To organize your data efficiently based on a specific character, you can use the split function followed by sorting. This code snippet demonstrates how to achieve this assuming your main data structure is referred to as "structure":

structure.forEach(section => {
    section.sectionRange.forEach(range => {
        range.items.sort(function(itemA, itemB) {
            let partsA = itemA.split("-"),
                partsB = itemB.split("-");
            
            return +partsA[0] - +partsB[0];
        });
    });
});

Answer №2

Simply extract the numerical values and let AngularJS's orderBy filter handle the sorting for you

JavaScript

  $scope.getNumber = function(row){
    var value = row.title.split("-")[0];
    return parseInt(value);
  };

HTML

<div ng-repeat="item in data | orderBy:getNumber:false">{{item.title}}</div>

The orderBy function also accepts a second parameter (true / false) for ascending / descending ordering

Check out the demo

Answer №3

To sort an array based on the numerical value of a specific property, you can utilize the Array.prototype.sort method along with a custom sorting function. In this case, you would need to extract and compare the numeric values from the 'title' property of each object within the array. Here's an example implementation:

var arr = [{
    "title": "1-Introduction"
  },
  {
    "title": "5-Introduction"
  },
  {
    "title": "20-Introduction"
  },
  {
    "title": "4-Introduction"
  }
];

arr.sort(function(a, b) {
  const aVal = parseInt(a.title.split("-")[0]);
  const bVal = parseInt(b.title.split("-")[0]);
  return aVal - bVal;
});

console.log(arr);

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

Passing conditional empty variables through `res.render`

I am currently facing a challenge with passing multiple variables into a res.render. One of the variables will have an object to send through, while the other may not have anything to pass. As a result, I am encountering an undefined error. Below is the ...

Is there a way to programmatically update the content of a React Bootstrap modal?

I have been attempting to modify the content of a modal after it has been loaded, but I am struggling to identify the correct nodes for modification. I have added references to the nodes I want to change and attempted to alter them in componentDidMount(). ...

Retrieve the URL with a GET request and remove a specific object

Currently, I am working on developing a CRUD (Create, Read, Update, Delete) App using Express and LowDB. So far, I have successfully implemented the create and read functions, but I am facing issues with the delete function. This is an example of what th ...

What is the best way to simulate mailgun.messages().send() with Jest?

Currently, I am utilizing the mailgun-js Api for sending emails. Instead of a unit test, I've created an integration test. I am now facing the challenge of writing a unit test case for the sendEmail method within the Mailgun class. I am unsure of how ...

Create a custom function that scans an array and retrieves the item for a specific animal name if it exists within the array

As someone new to learning JavaScript, I have encountered a challenge that has left me stumped for quite some time. My task involves working with an array containing objects representing different animals, including details such as their species, names, ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

Steps for refreshing a JavaScript function responsible for generating a table

Within the code snippet provided, there is a click event attached to a table row. Upon clicking a row, the script extracts the id value from the first column and triggers a REST call. Subsequently, a new table is constructed using a third-party function ca ...

Seeking assistance with java.lang.ArrayIndexOutOfBoundsException in Java programming

I've been working on some basic Java game code and I'm struggling to find a solution for my issue. Here is the code snippet: [GameWindow.java] package my.project.gop.main; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; i ...

Switching an input field from readonly to editable in ASP.NET Core

MODAL <div class="modal fade" id="residentModal" tabindex="-1" role="dialog" aria-labelledby="residentModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg& ...

Leveraging the power of AJAX to dynamically update information on a modal form using PHP's

After successfully preventing my modal form from closing upon submitting a value using ajax jQuery without refreshing the page, I encountered a new issue. Whenever I fill in my modal form and click submit to update the data inside my database, it does not ...

Attempting to keep a:active state active until another link is clicked

My goal is to have two links, "hot" and "update." When "hot" is clicked, it should turn red and "update" should turn black. Conversely, when "update" is clicked, it should turn red and "hot" should turn black. This functionality works perfectly on a Fiddl ...

Jquery problem: dealing with empty spaces

I am working on a project where I need to use jQuery to disable specific input fields, like the following: $("input[value=" + resultId[i].name + "]" ).prop('disabled', true); $("input[value=" + resultId[i].name + "]" ).css({ 'background-col ...

Creating hierarchical dictionaries in Python for use with the json.dump function

I am looking to write a set of Python lists serially in a JSON file with a specific structure. The structure is outlined below: [ { "_id": { "$oid": "5707b5f4e4b0c4265caf3c87" }, "TimeStamp": 1, "TraceData": [ { ...

The if-else condition is creating issues with the functionality of the buttons

Update #1 - Enhanced query, fresh functional link. Live site: The challenge at hand revolves around an if-else statement related to the form buttons on the right-hand column of the webpage. Scroll past the header and navigation to witness the issue in ...

What is the best way to bypass array values in PHP?

Seeking assistance with an array: Array ( [0] => 2 [1] => 2 [2] => 1 [3] => 1 [4] => 2 [5] => 2 ) Exploring the use of a foreach loop: foreach( $valortot as $key => $m ) { $valortot[$key]; echo $valortot[$key]; echo "<br>"; } T ...

Padding an array with zeros along a specific axis

I need to pad the following array: [[1, 2] [3, 4]] so that it becomes: [[0, 0, 0] [0, 1, 2] [0, 3, 4]] I can easily achieve this with vstack and hsrack when working with a 2D input. However, I encounter an issue when adding an extra dimension to re ...

Designing draggable divs that overlap each other

When a button is clicked, a new div is dynamically created. Using the jqueryui draggable PLUGIN, each div becomes draggable. However, there is an issue when trying to stack one div on top of another; the latest div created remains on top and cannot be over ...

Expandable Grid with UI-GRID - Automatically expand a row when clicked on

I prefer not to utilize the default + icon for expanding the row. The row should expand when clicked anywhere on it. I attempted the following: HTML <div ui-grid="gridOptions" ui-grid-expandable class="grid"> Controller var app = angular.module( ...

The connection to MongoDB is failing due to an incorrect URI

I tried setting up mongoDB on my node server and referred to the official MongoDB documentation. Here are the details of my setup: MongoDB version: 4.4.3 Node.js version: v15.7.0 I copied the starter code from MongoDB and here is what I used: const { Mon ...

PHP-powered interactive web application driven by REST API

I am currently in the process of creating a REST-Centric web dashboard using PHP. My main goal is to ensure that data is exchanged solely through REST calls without any direct database connections. I have explored various frameworks such as slim, silex, ...