Sorting by default in Javascript and Typescript

I'm currently exploring TypeScript and I'm puzzled by the behavior of the code snippet I've shared here: https://codepen.io/anon/pen/EpVMJX. In this code, I noticed that the test array's order changed after I sorted it, even though I stored the result in the 'res' variable. Initially, I thought that the sorting operation automatically modifies the original array. However, I also attempted to create a copy of the original array in a new variable called 'defaultArr' before sorting, and it too changed its order.

let arr:any = [
            { count: 13, year: '1956' },
            { count: 1, year: '1971' },
            { count: 23, year: '1989' },
            { count: 11, year: '1988' }];
let defaultArr = arr;
async function foo(){
  console.log(defaultArr);
  console.log(arr);
  let res = arr.sort((n1,n2)=> n1.count > n2.count? -1:1);
  console.log(res); 
}
foo();

How can I prevent the original array from changing its order?

Answer №1

My initial assumption was that the sorting process automatically alters the sorted array itself.

Indeed, sort modifies the array it is called on. The return value simply points to the same array for convenience.

However, I also attempted to duplicate the original array into another variable (defaultArr) before sorting, but it still ended up having its order changed.

In reality, you did not duplicate the array; you merely duplicated the reference to the array. Consequently, both arr and defaultArr ended up referencing the same array object:

slice:

defaultArr = arr.slice();

Additionally, a couple of points to consider:

  • There is no necessity for foo to be declared as async since it does not involve any asynchronous operations.
  • Your sort callback is flawed as it does not account for instances where the counts are equal.

Below is your updated example, where the array is copied, foo is no longer async, and the sort callback is corrected (refer to the comments within the code for further clarification):

let arr = [
            { count: 13, year: '1956' },
            { count: 1, year: '1971' },
            { count: 23, year: '1989' },
            { count: 11, year: '1988' }];
// This function does not need to be `async`
function foo(){
  let res = arr.slice();
  // The return value of `sort` should be less than zero if n1 should precede n2,
  // greater than zero if n1 should follow n2,
  // or zero if they are deemed equal for sorting purposes.
  // By using n2.count - n1.count, we obtain this number directly.
  res.sort((n1,n2) => n2.count - n1.count);
  console.log(res); 
}
foo();
.as-console-wrapper {
  max-height: 100% !important;
}

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

Exploring the methods of connecting with data-checked and data-unchecked attributes in Angular

Utilizing a toggle switch, I am able to determine what text to display in the div by utilizing html attributes such as data-checked and data-unchecked. In addition, I have an Angular pipe that translates all texts on the website based on the selected lang ...

Nextjs REACT integration for self-service registration through OKTA

Attempting to integrate the Okta SSR feature for user sign-up in my app has been challenging as I keep encountering this error message: {"errorCode":"E0000060","errorSummary":"Unsupported operation.","errorLink& ...

Encountering 'null' error in template with Angular 4.1.0 and strictNullChecks mode

After updating Angular to version 4.1.0 and activating "strictNullChecks" in my project, I am encountering numerous errors in the templates (.html) that look like this: An object may be 'null' All these errors are pointing to .html templat ...

What are the steps to set up ChartJS on a personal computer?

Currently, I am working on creating charts with ChartJS using the CDN version. However, I would like to have it installed directly on my website. After downloading ChartJS v4.1.1, I realized that it only contains typescript files. Since I cannot use TS fil ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

Unable to download tsc through the Terminal on OS X

Struggling to install tsc, encountering numerous errors upon running it. Reinstalled node and npm multiple times, adjusted npm flag to verbose, here's the output: Mitch:~ mitch$ npm install -g typescript npm info it worked if it ends with ok ... Fe ...

Tips for accessing the app instance within a module in Nest.js

Currently, I am involved in a project that relies on multiple Nest repositories, approximately 4 in total. Each repository must integrate logging functionalities to monitor various events such as: Server lifecycle events Uncaught errors HTTP requests/resp ...

The ng2-chart library displays date in the form of a Unix timestamp

I have a date object imported from my database, but it is showing up as a Unix timestamp (-62101391858000). I know I can format the date using pipes like {{myDate | date:medium}}, however, I am using ng2-charts so I need to find a different solution. My ch ...

"Unlocking the full potential of Typescript and Redux: Streamlining the use of 'connect' without the need to

I am facing some challenges with typescript and redux-thunk actions. The issue arises when my components heavily rely on react-redux connect to bind action creators. The problem occurs when I create the interface for these redux actions within the compone ...

Obtaining attributes of a class from an object passed into the constructor

Consider the following code snippet: interface MyInterface { readonly valA: number; readonly valB: number; } class MyClass { readonly valA: number; readonly valB: number; constructor(props: MyInterface) { this.valA = props.val ...

Using Typescript to set the image source from a pipe

I've been working on creating a custom pipe similar to the code below: @Pipe({ name: 'imagePipe' }) @Injectable() export class ImagePipe { constructor(public someService: SomeService, public storage: Storage) { } transform(value: ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. https://i.sstatic.net/0dfxd.png Click here for image description However, we are looking to transition this functionality ...

Unable to include option object in the SHA3 function using typescript

The SHA3 function allows for customizing the output length, as demonstrated in the code snippet below: var hash = CryptoJS.SHA3("Message", { outputLength: 512 }); var hash = CryptoJS.SHA3("Message", { outputLength: 384 }); var hash = CryptoJS.SHA3("Messag ...

An error has occurred: Type 'x' is not compatible with type 'x' (during Vercel deployment)

I encountered an issue during Vercel deployment which displays the following error message: - Type error: Type ' ({ params }: DashboardPageProps) = Promise' is not compatible with type 'FC<.DashboardPageProps>' Type 'Promise ...

What is the method for transmitting a concealed attribute "dragable" to my component?

Currently, I have successfully integrated a here map into my project, but I am now tackling the challenge of adding draggable markers to this map. To achieve this, I am utilizing a custom package/module developed by my company. This package is designed to ...

Playwright failing to execute GraphQL tests due to TypeScript configuration problems

I'm facing an issue with my repo where I am running tests using Playwright against a graphQL URL. Despite configuring the tests, there is an error indicating that the environment variable defining the environment cannot be found. The repository in qu ...

Experiencing a hitch when attempting to deploy an Angular 2 application on Heroku

Encountering the sh: 1: tsc: not found Error when attempting to deploy an Angular 2 app on Heroku. Using Node version: v7.2.0 and npm Version: v4.0.3. View the error on Heroku Any suggestions on how to resolve this issue? ...

Does the routing in Angular 2 get disrupted by parameter breaks in sub-modules?

In my Angular 2 application, I am encountering an issue with routing to my line module. Currently, I have two submodules - login and line. The routing to the login submodule is working well. However, when I attempt to route to the line module with route pa ...

Angular Tutorial: Understanding the Difference Between TypeScript's Colon and Equal To

I've been diving into the Angular4 tutorial examples to learn more about it. https://angular.io/docs/ts/latest/tutorial/toh-pt1.html One of the code snippets from the tutorial is as follows: import { Component } from '@angular/core'; @Co ...

Using Next.js, it is not possible to use absolute imports within SASS

Having trouble utilizing @/ imports within my scss files. The variables I need are stored in src/styles/_variables.scss Here is my tsconfig.json: { "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "baseUrl": ".", "allowJs": tr ...