sort by the last element in the array

I have implemented an angular table that is organized by an array. The structure is such that the second level depends on the first level, and the third level depends on the second, and so forth.

For instance:

A is the parent of B, B is the parent of C.

The ordering works perfectly until the point where I want to reverse it. At that stage, I only want the last child (in the above example, C) to be reordered, while both A and B remain unchanged.

Is this achievable? If yes, how can I do it?

In the plunker link provided below, I aim to change the order of the rows with C when clicking the button.

http://plnkr.co/edit/bCwdIg3MNHVdfaX1hvni?p=preview

<!doctype html>
<html lang="en">
   <head>
      <meta charset="UTF-8>
      <title>Example - example-example105-production</title>
      <link href="style.css" rel="stylesheet" type="text/css">
      <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
      <script src="script.js"></script>
   </head>
   <body ng-app="orderByExample">
      <div ng-controller="ExampleController">
         <table class="friend">
            <tr>
               <th>
                  <button ng-click="toggle_order()">switch order</button>
                  <span class="sortorder" ng-show="predicate === 'group'" ng-class="{reverse:reverse}"></span>
               </th>
            <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
               <td>{{friend.group}}</td>
            </tr>
         </table>
      </div>
   </body>
</html>

JavaScript:

(function(angular) {
    'use strict';
    angular.module('orderByExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
            $scope.friends = [{
                group: ['A']
            }, {
                group: ['A', 'B1']
            }, {
                group: ['A', 'B1', 'C1']
            }, {
                group: ['A', 'B1', 'C2']
            }, {
                group: ['A', 'B1', 'C3']
            }, ];
            $scope.predicate = 'group'
            $scope.reverse = false;
            $scope.toggle_order = function() {
                $scope.reverse = !$scope.reverse;
            };
        }]);
})(window.angular);

Answer №1

This code example utilizes plain Javascript.

It employs a custom sorting method that arranges arrays of unequal length by their length in ascending order, and then sorts the remaining elements starting from the rightmost part in descending order.

var data = [
        { group: ['A', 'B1', 'C2'] },
        { group: ['A', 'B1'] },
        { group: ['A', 'B1', 'C1'] },
        { group: ['A'] },
        { group: ['A', 'B1', 'C3'] }
    ];

data.sort(function (a, b) {
    var l = Math.min(a.group.length, b.group.length),
        r = a.group.length - b.group.length;

    while (!r && l--) {
        r = b.group[l].localeCompare(a.group[l]);
    }
    return r;
});

document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

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

Discovering the Cookie in Angular 2 after it's Been Created

My setup includes two Components and one Service: Components: 1: LoginComponent 2: HeaderComponent (Shared) Service: 1: authentication.service Within the LoginComponent, I utilize the authentication.service for authentication. Upon successful authent ...

Use AngularJS to integrate ArcGIS JS 4 API and showcase a dynamic map on your webpage

I'm just beginning to learn ArcGIS JS and I would really appreciate any assistance. My initial goal is to showcase a map using ArcGIS JS API 4 with AngularJS. Any guidance or sample code would be greatly appreciated. Thank you ...

My loop encountered an 'Undefined' error while attempting to retrieve an object from a JSON file

Hey everyone, I could use some help with a problem I'm having in my for loop. The issue is that I keep getting an "undefined" word in the output of my loop. I am trying to retrieve objects from a JSON file and the loop itself seems to be working corre ...

What is the best way to initiate a local Node.js server specifically when launching a desktop Electron application?

I am looking to ensure that my node js server runs while my electron app is open. One method I have attempted is using the child_process module to execute a shell command as shown below: const {exec} = require('child_process') const startDBServ ...

Enhancing webpage styles with AngularJS

Just starting out with AngularJS and eager to get the best approach to tackle this challenge. Describing my dilemma: I have an anchor element that, when clicked, needs to toggle between classes "show-all" and "hide-all" while also updating the styling of ...

The module 'react/jsx-runtime' could not be located within the path relative to '@mui/styled-engine/StyledEngineProvider/StyledEngineProvider.js'

I encountered this issue when attempting to create a new React project using MUI. I followed this code example from the documentation, which functions correctly in their live Codesandbox but not on my local setup. Here is the complete error message: Module ...

In Node.js, the mongodb+srv URI does not support including a port number

Currently, I am working on a project in nodejs using express js. I have encountered the following error: MongoDB connection error: MongoParseError: MongoDB+srv URI cannot contain a port number. In my "MongoDB Atlas" dashboard, I have obtained my "connecti ...

Change the height of textarea dynamically using jQuery

I am trying to create a comment box similar to Facebook's, where it resizes as text fills it using Expanding Text Areas Made Elegant This is how my view looks: <div class='expandingArea'> <pre><span></span></ ...

CSS2DRenderer Reset Feature

My scene, camera, renderer, and CSS2DRenderer are created using this class. I am looking for a way to reset (delete and add again) my CSS2DRenderer in order to remove any previously rendered CSS2DObject. Can you guide me on how to achieve this properly? T ...

Exploring the process of defining and authenticating an array of objects utilizing cuid as the key and ensuring the object contains designated properties

I have a customized data set that requires validation: { "name": "Some unique name", "blocks": [ {"cj5458hyl0001zss42td3waww": { "quantity": 9, "rate": 356.77, ...

Manipulating Data in AG-GRID with AngularJS: A Guide to External Editing

Currently, I'm in the process of developing a single-page application that utilizes AngularJS, UI-Router, and AG-GRID. However, I've encountered an issue with updating AG-GRID's data from an external form. Here is a breakdown of the problem ...

I'm having trouble with my bootstrap dropdown and I've exhausted all of my options trying to fix it based on my current understanding

My dropdown menu is not working despite adding all necessary Bootstrap CDN and files along with the jQuery script. Even with the table being handled by JavaScript, the button does not respond when clicked repeatedly. I suspect the issue lies within the han ...

Unlocking the potential: passing designated text values with Javascript

In my current React code, I am retrieving the value from cookies like this: initialTrafficSource: Cookies.get("initialTrafficSource") || null, Mapping for API const body = {Source: formValue.initialTrafficSource} Desired Output: utmcsr=(direct)|utmcmd=(n ...

li rel=identifier

Can someone assist with choosing rel="28700" in order to update the text within the <li> tag? <li id="pen_li_8" rel="28700"><span class="linkselectValue">Text to be changed</span></li> I have attempted the obvious method: $ ...

Issue with Bootstrap tab display of content

I'm having trouble with the tabs in my page. When I click on each tab, the content doesn't display correctly. Here is my code: <div class="w470px exam" style="border: 1px solid #ddd; margin-top: 30px;"> <ul id="myTab" class="nav nav ...

Attempting to access an avatar image via an API, only to encounter an error message indicating that the avatar is not defined

userData is a function that retrieves user data from an API using getUserByChainAccount. The username required by getUserByChainAccount is dynamically fetched from buyer. I'm trying to access the avatar, but I keep encountering the error message Unha ...

jquery accordion failing to display content

Upon navigating to my website and accessing the webpage featuring an accordion, the accordion successfully appears and hides after 1500ms as intended. However, when attempting to reveal the text by clicking on the headings, nothing happens. The heading sim ...

Exploring the functionality of dynamic component imports in jest testing

Under a specific condition, I dynamically imported a component and stored it in an object property. Then, I displayed it in the template using vue <component :is="">. Everything is functioning correctly at the component level. However, I am ...

Ways to make nodejs return a different value instead of an object promise

Within my user.js file, I have an async function designed to retrieve the avatar's location from the database. The code for this operation is as follows: async findavatar(username) { const sql = `SELECT image FROM users WHERE user = "${userna ...

Apply styles specifically to elements that contain a child element

I have a scenario where there are multiple <p> elements with the same class names, but only one of them has a child element. My objective is to highlight only the <p> that contains a child, however, my current code ends up highlighting all of t ...