What is preventing me from sorting multiple times?

My current challenge involves sorting an array of data multiple times for different purposes. While I could choose to save the sorted data on the back end, I prefer handling it this way.

However, I have encountered a problem where only one sort operation seems to be effective, as shown in the following example: this is the component



export class xService {
  comp$: Observable<any[]> | undefined;
  c1 = new Array();
cp1 = new Array();
at_b3 = new Array();
at_b = new Array();
at_b2 = new Array();

  constructor(public a_s: AServ, private db: AngularFireDatabase) {

    this.comp$ = this.a_s.xc$.pipe(switchMap((x) => {
      return this.db.list('people/'+x).valueChanges();   
      }));

      this.comp$.subscribe({next: (value) => {
this.c1 = value[0];
this.cp1 = value[0].users;
this.at_b3 = value[0].users;

this.a_s.statsa.push(value[0].users);

  this.at_b = this.cp1.sort((a: any, b: any) => Number(a.stats[0].day_off) - Number(b.stats[0].day_off)).reverse();
  this.at_b2 = this.cp1.sort((a: any, b: any) => Number(a.stats[0].places_went) - Number(b.stats[0].places_went)).reverse();
  
  console.log(this.at_b)
  console.log(this.at_b2)


      }
    });


   }
}

Specifically, I am facing issues with the following code snippet:


  this.at_b = this.cp1.sort((a: any, b: any) => Number(a.stats[0].day_off) - Number(b.stats[0].day_off)).reverse();
  this.at_b2 = this.cp1.sort((a: any, b: any) => Number(a.stats[0].places_went) - Number(b.stats[0].places_went)).reverse();

Despite my efforts, when attempting to render or utilize console logs, I am unable to access two distinct arrays; instead, I seem to retrieve the same array repeatedly.

Answer №1

To ensure proper sorting, it is important to create copies of the arrays before applying the sort function:

export class xService {
  comp$: Observable<any[]> | undefined;
  c1 = new Array();
  cp1 = new Array();
  at_b3 = new Array();
  at_b = new Array();
  at_b2 = new Array();

  constructor(public a_s: AServ, private db: AngularFireDatabase) {
    this.comp$ = this.a_s.xc$.pipe(
      switchMap((x) => {
        return this.db.list("people/" + x).valueChanges();
      })
    );

    this.comp$.subscribe({
      next: (value) => {
        this.c1 = value[0];
        this.cp1 = value[0].users;
        this.at_b3 = value[0].users;

        this.a_s.statsa.push(value[0].users);

        this.at_b = [...this.cp1]
          .sort(
            (a: any, b: any) =>
              Number(a.stats[0].day_off) - Number(b.stats[0].day_off)
          )
          .reverse();
        this.at_b2 = [...this.cp1]
          .sort(
            (a: any, b: any) =>
              Number(a.stats[0].places_went) - Number(b.stats[0].places_went)
          )
          .reverse();

        console.log(this.at_b);
        console.log(this.at_b2);
      },
    });
  }
}

Note:

  • Array.prototype.sort() will sort the array in place and return the sorted array.

  • It is crucial to remember that calling sort() directly modifies the original array. By creating copies of the arrays beforehand, such as this.cp1, you can avoid unintended side effects and ensure accurate sorting results for both this.at_b and this.at_b2.

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

Angular's Enhanced Feature: Selecting Multiple Columns

Looking for an open-source Angular library that can display items in multiple columns rather than each item spanning across multiple columns. Many libraries support tabular display, but the challenge is to find one that arranges items in multiple columns. ...

Error encountered in Typescript: SyntaxError due to an unexpected token 'export' appearing

In my React project, I encountered the need to share models (Typescript interfaces in this case) across 3 separate Typescript projects. To address this, I decided to utilize bit.env and imported all my models to https://bit.dev/model/index/~code, which wor ...

Looking for a way to find index-based values within a table using Angular 4?

I am currently using angular 4 and have created an array with a list of values. However, I am encountering an error when trying to search based on the index. How can I effectively search for index-based values? ang.html: <div class="col-md-6" > &l ...

Viewing Image in Modal on Click

Despite numerous attempts, I have been unable to make this work, even after trying various examples. The issue at hand is with a list of imageURL's that are displayed on the webpage. The goal is to allow users to click on an image, which would then o ...

Loading only specific HTML list elements in segments

Within my Angular4 application, I am faced with a challenge involving a large list of li elements. The browser struggles to handle the thousands of li's being displayed when the user interacts with the ul element. This results in slow loading times an ...

Determine the average value and handle any NumberFormatException

Create a program that takes in a series of 10 integers from the user and calculates their average. Each input value is initially read as a string and then converted to an integer using the Integer.parseInt method. If the conversion process results in a Num ...

Program ended unexpectedly due to segmentation fault (core dumped) in a simplistic code

I encountered a challenging issue while working on a simple program to grasp arrays in C. The problem arises when the array size is set to more than 2. Operating System: Linux, Clear Linux OS 64 bits #include <stdio.h> int main (void) { int arra ...

Updating a record in a Node.js Express API using TypeScript version 3

I successfully set up a Node.js Express API with TypeScript 3 and it is running smoothly. However, I encountered an issue when attempting to update a record. Here is the content of RecordsRouter.ts: import { Router } from 'express'; import {Reco ...

What is the best approach for implementing recursion within a foreach loop in TypeScript?

Problem Situation I am attempting to develop a customized typewriting effect similar to the one demonstrated here with a 100ms delay using Angular. The TypeScript code I have written for this purpose is as follows: private arr: string[] = ["Lead Dev ...

Demystifying the Mechanics of RxJS Subscriptions during an HTTP Request

export class VendorHttpService { result = '0'; constructor(private http: HttpClient, private global: GlobalService) { } getProfileStatus(uid: String): string { this.http.get(this.global.getUrl()+"/vendor/profile-status/"+uid) ...

Translation of country codes into the complete names of countries

Currently, my code is utilizing the ipinfo.io library to retrieve the user's country information successfully. This is the snippet of code I am using to fetch the data: $.get("https://ipinfo.io?token=0000000000", function(response) { console.log ...

What is the best way to select types conditionally based on the presence of a property in another type?

To begin with, I have a specific desired outcome: type Wrapper<ID extends string> = { id: ID }; type WrapperWithPayload<ID extends string, Payload> = { id: ID, payload: Payload }; enum IDs { FOO = "ID Foo", BAR = "ID Bar", BAZ = "ID Baz ...

PHP: What is the method of passing array elements to the value comparison function in usort()?

Seeking clarity on the mechanism by which values from an array are sent to the value comparison function when utilizing usort(). Below are the values of $x and $y for each iteration: Iteration 1: // $x array(2) { ["k1"]=> int(21) ["k2"]=> string(1) ...

Ways to retrieve the index of a randomly selected JSON file from a list

I'm currently working on a script for a book selection randomizer and I'm trying to figure out how to also display the index number of the chosen book from a JSON list. Here is my function for displaying all the data: def view_data(): with open ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Mo ...

Failure of Angular guard to retrieve information

Using the google maps API, I retrieve maxLat, maxLng, minLat, and minLng to fetch data from the database before generating the component, in order to optimize SEO meta tags and descriptions. The issue I encountered is that the guard resolves the data but ...

I am struggling with implementing an array in Python

Having trouble manipulating text from a word file, I noticed that when trying to save it to an array of classes, all the indexes are getting overwritten instead of just one specific index. for line in modified: if line.startswith('Date'): ...

A comprehensive guide on creating and searching for tables in Angular

Seeking guidance on creating a table in Angular to display data fetched from an API. Currently developing a library management project with a reservation feature for books. Working on the search page where users can search and view book information in a ta ...

New in the latest release of Angular2 (rc6): Expansion of RouterOutlet with the addition of the

Currently, I am working with angular2 rc6 and I'm open to utilizing the latest release that has been announced. My goal is to set up the router outlet feature in a way that only authenticated users can access it. This piece of code below was function ...