Revamping elements according to ordered array. Angular version 4.3

Dealing with an array of data that needs to be sorted for displaying in a component seems to be a challenge. Despite having a functional code sample demonstrating the concept, the sorting is not reflected in the Angular app's DOM.

The original data is stored in a parent component's Input parameter object called Batch, while the array intended for sorting can be found within Batch.Invoices.Results. The event propagation from the child component to the parent works correctly as expected.

The function responsible for sorting the array is outlined below:

 public OnInvoiceSortChange({orderValue, orderAscending}){
        console.log(`Invoice Sorting has been called. Value: ${orderValue} . Ascending? ${orderAscending}`);
        console.log(`Before:`);
        console.log(this.BatchViewModel.Invoices.Results.map(x => x.VendorName));
        const sortingArray = [...this.BatchViewModel.Invoices.Results];
        if(orderAscending){
            const sorted = sortingArray.sort((a, b) => a[orderValue] > b[orderValue] ? 1 : 0);
            this.BatchViewModel.Invoices.Results = sorted;
            console.log('Sorted');
            console.log(sorted.map(x => x.VendorName));
        } else {
            const sorted = sortingArray.sort((a, b) => a[orderValue] < b[orderValue] ? 1 : 0);
            this.BatchViewModel.Invoices.Results = sorted;
            console.log(sorted.map(x => x.VendorName));
        }
        console.log(`After:`);
        console.log(this.BatchViewModel.Invoices.Results.map(x => x.VendorName));
    }

The console logs provide visibility for debugging purposes and generate this output: https://i.sstatic.net/Y9pE6.png

A similar scenario tested outside of Angular (using data directly copied from the Angular app) shows the following pattern:

const ascendingData = [...data];
const descendingData = [...data];

const sortedDescending = descendingData.sort((a, b) => a['VendorName'] < b['VendorName']? 0 : 1)
const sortedAscending = ascendingData.sort((a, b) => a['VendorName'] > b['VendorName']? 0 : 1);

const vendorListAscending = sortedAscending.map(x => x.VendorName);
const vendorListDescending = sortedDescending.map(x => x.VendorName);

console.log(vendorListDescending);

console.log(vendorListAscending);

This produces the following output:

https://i.sstatic.net/iUVnD.png

While the testing file suggests successful sorting, the issue persists within Angular. Any suggestions on how to effectively sort the array and update the DOM accordingly?

Answer №1

The sort function you provided is incorrect. It should return a negative value for "less", a positive value for "greater", or zero for "equal". If the orderValue parameter is numeric, you can simply use a[orderValue] - b[orderValue], otherwise, replace 0 with -1.

(By the way, perhaps consider using a clearer name than orderKey?)

It seems unrelated to Angular, but I'm not sure why you're experiencing different results. Your current sort function has a flaw (it claims that a equals b, yet also implies that b is greater than a). Fixing this issue should address the problem.

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

Mastering the implementation of opaque tokens in Angular 2

Hey there! I'm having trouble with opaquetoken, is there something I missed? Check out my Plunk example here. Here's the relevant code snippet from app.ts: export const SbToken = new OpaqueToken('myToken'); const testfile = 'Hel ...

What is the best way to include a disable option or default option in a select box?

I am incorporating react material in react using the select component. My goal is to include a first disabled option that says "please select item." This is how it's currently implemented in HTML: <select name="tagging"> <option sel ...

Why does TypeScript keep throwing the "No inputs were found in the config file" error at me?

Why am I receiving the No inputs were found in config file error from TypeScript? I have set up my tsconfig.json in VS Code, but the error occurs when I try to build it. The terminal displays: error TS18003: No inputs were found in config file '/Use ...

Build a row within an HTML table that is devoid of both an ID and a class

Creating an additional row in an HTML table is a common task, but it can become tricky when dealing with multiple forms and tables on one page. In my case, I have a form that contains only a table element, and I want to move some columns from the first row ...

Using Reactjs to automatically populate text into a React-Select Input field

I have implemented react-select in my project. Sometimes, I encounter the need to update my react-select input field without directly interacting with it (such as injecting text into it). However, I am unable to find a proper way to achieve this based on ...

Retrieve no data from Firebase using Cloud Functions

I am a beginner with Google Firebase and Cloud Functions, and I recently attempted a basic "hello world" program: Established a connection to Cloud Firestore [beta], which contains over 100,000 records. Retrieved the top record from the database. Below ...

Encountering this issue despite confirming the presence of data on the line before! What could be the missing piece here? Error: Unable to access property 'includes' of undefined

Here is the situation.. I'm retrieving data from a database and storing it in an array of objects. These objects represent articles. I am working on implementing a filter system based on categories. The objective is to apply a filter that checks for a ...

When the window is fully loaded, JavaScript executes

Can someone help me set up this script to start running when the page loads? I want the vat field to automatically show up if the company name has been entered. Thank you! //--></script> <script type="text/javascript>//-- $('.colorbox ...

Angular material 10 is having trouble fetching the icon named "mysvg". It seems that a user login is needed

Unfortunately, I am unable to replicate this issue in my project as I utilize authn/authz. The problem seems to be related to a custom SVG. Below is the IconService code snippet: @Injectable({ providedIn: "root", }) export class IconService { construc ...

Ways to abbreviate a URL using Next JS

While working on my Next.js application, I encountered an issue with passing an object between pages. To achieve this, I compressed my array of objects into JSON using JSON.stringify(result) on the index page and then parsed it on the second page using JSO ...

jQuery issue: Inability of "Read More" span to reappear after clicking "Read Less"

Currently in the process of creating a portfolio website that showcases project descriptions with an excerpt, revealing full details upon clicking "Read More." My experience with jQuery is limited, but I managed to implement functionality where clicking "R ...

Implementing dynamic webpage updates based on dropdown list selections

In my webpage, I am displaying a list of movies fetched from an API. The issue I am facing is related to sorting the movies based on user selection. When I uncomment one of the sort methods in my code, it works as intended. What I want to achieve is that ...

What steps can be taken to restrict users to providing only one comment and rating for each item?

In the backend controller, I have the following code snippet: 'use strict'; var Comment = require('../../../models/comment'); module.exports = { description: 'Create a Comment', notes: 'Create a comment&apos ...

What could be the reason for Jest flagging CSS as untested instead of identifying untested functions?

While working on my vue3 project and writing tests with jest, I have encountered an issue where jest is incorrectly marking the CSS within several single file components as untested, even though it doesn't need to be tested. Moreover, its assessment ...

Determine the position within the DOM of a webpage and dynamically update the navigation menu classes to reflect the changes

Help! I am trying to create a navigation menu with links that direct users to specific parts of my page. I want to use JavaScript to add a class to each navigation menu item when the scroll bar reaches the corresponding section in the HTML. I think I know ...

What is the best way to save the properties of elements in an array of objects within another array?

I have obtained attributes from objects within an array that I need to store in another array. Here is the data I am working with: My goal is to extract the `displays` name attribute and save it in the `opt[]` array, which would result in something like t ...

What are the best methods for protecting a soda?

My code is in strict mode, and I am encountering an issue with the following snippet: const a: string[] = []; // logic to populate `a` while (a.length > 0) { const i: string = a.pop(); // This line is causing an error console.log(i); // additio ...

What's the best way to update the value of an angular field upon submission?

Could someone please provide instructions on how to update the myName variable when the "submit" button is pressed? Thank you! app.js: app.controller('SomeController', ['$scope', 'emails', function($scope, emails) { emails ...

Developing a custom React component library using Webpack and Typescript, however encountering issues with Webpack consistently bundling React

I'm currently in the process of developing an external component library using Webpack and TypeScript. Although it compiles without any issues, I encounter an error when attempting to use the library: Invalid hook call. Hooks can only be called ins ...

Having issues with Angular chart.js onClick event? Learn how to retrieve all elements of a bar when it is clicked on

As a newcomer to Chart.js, I am exploring how to implement click events for when a chart is generated. My current challenge involves accessing all the elements of a bar upon clicking it. Unfortunately, the onClick method is not functioning as expected at ...