What is the best way to arrange an array in either javascript or typescript based on a specific key, and in the case of identical keys,

Below is an array with objects that need to be sorted:

[   
  {
    "Books": [],
    "_id": "5dea9a11a8e1bf301c462ce4",
    "FileName": "AAAAA",
    "Order": 99999
  },
  {
    "_id": "5dea9864a8e1bf301c462cdb",
    "Books": [],
    "FileName": "some1",
    "Order": 3
  },
  {
    "Books": [],
    "_id": "5dea9873a8e1bf301c462ce1",
    "FileName": "among3",
    "Order": 3
  },
  {
    "Books": [],
    "_id": "5dea986ba8e1bf301c462cde",
    "FileName": "things2",
    "Order": 2
  },
  {
    "Books": [],
    "_id": "5dea9a18a8e1bf301c462ce7",
    "FileName": "FFFF",
    "Order": 99999
  },
  {
    "Books": [],
    "_id": "5dea9a1ea8e1bf301c462cea",
    "FileName": "BBBB",
    "Order": 99999
  }
]

The goal is to sort the array by Order first, and if the Order values are the same, then sort alphabetically by FileName.

[
 {
    "Books": [],
    "_id": "5dea986ba8e1bf301c462cde",
    "FileName": "things2",
    "Order": 2
  },
    {
    "Books": [],
    "_id": "5dea9873a8e1bf301c462ce1",
    "FileName": "among3",
    "Order": 3
  },
    {
    "_id": "5dea9864a8e1bf301c462cdb",
    "Books": [],
    "FileName": "some1",
    "Order": 3
  },
  {
    "Books": [],
    "_id": "5dea9a11a8e1bf301c462ce4",
    "FileName": "AAAAA",
    "Order": 99999
  },
  {
    "Books": [],
    "_id": "5dea9a1ea8e1bf301c462cea",
    "FileName": "BBBB",
    "Order": 99999
  },
   {
    "Books": [],
    "_id": "5dea9a18a8e1bf301c462ce7",
    "FileName": "FFFF",
    "Order": 99999
  },
]

I have managed to achieve this using multiple loops but seeking an optimized solution. Any suggestions or optimized JavaScript/TypeScript code would be greatly appreciated. Thanks!

Answer №1

When it comes to testing, the order matters just as much as the string itself.

const data = [   
  {
    "Books": [],
    "_id": "5dea9a11a8e1bf301c462ce4",
    "FileName": "AAAAA",
    "Order": 99999
  },
  {
    "_id": "5dea9864a8e1bf301c462cdb",
    "Books": [],
    "FileName": "some1",
    "Order": 3
  },
  {
    "Books": [],
    "_id": "5dea9873a8e1bf301c462ce1",
    "FileName": "among3",
    "Order": 3
  },
  {
    "Books": [],
    "_id": "5dea986ba8e1bf301c462cde",
    "FileName": "things2",
    "Order": 2
  },
  {
    "Books": [],
    "_id": "5dea9a18a8e1bf301c462ce7",
    "FileName": "FFFF",
    "Order": 99999
  },
  {
    "Books": [],
    "_id": "5dea9a1ea8e1bf301c462cea",
    "FileName": "BBBB",
    "Order": 99999
  }
];

const sortDelegate = (a,b) => {
  const o = a.Order - b.Order;
  if(o === 0) {
    return a.FileName.localeCompare(b.FileName);
  } 
  return o;
};

console.log(data.sort(sortDelegate));

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

I'm having trouble sending a POST request using nodejs

Trying to send an app.post request with Postman, but encountering some issues. Here's the code snippet: const express = require('express'); const PORT = 8080; const HOST = '0.0.0.0'; const app = express(); app.listen(PORT, HOST) ...

How can Angular display an alert when no items are visible?

I want to display a message saying "Item doesn't exist" when the item is not found. Suppose this is my list: user 0 user 1 user 2 The following code displays the list above: <ng-container *ngFor="let user of users | async; let i = index"> ...

Unexpected unhandled_exception_processor in Google Chrome

I keep encountering a strange uncaught exception handler in Google Chrome. After updating all follow buttons to download JavaScript asynchronously, I noticed an error in the content.js file mentioned in the exception message which advises against polluting ...

customizing highcharts title within a popup window

Is there a way to dynamically set the title of a Highcharts chart from an element? Check out my code snippet below: $(function () { var chart; $('#second-chart').highcharts({ chart: { type: 'bar' }, subtitle: { ...

By changing the name of my file to .js.erb, I am able to seamlessly incorporate erb syntax within my javascript code, but this

Currently, I am using chessboard-0.3.0.js in a rails application. Due to the rails asset pipeline setup, I've had to make adjustments to the js code specifically related to rendering images, such as Pieces. In line 445 of chessboard.js, it states: c ...

Looping the Connection between Socket.io and Node

I have encountered a problem with my Unity client connecting to my node server using socket.io. While the initial connection is successful and acknowledged, when I try to emit a message to the connected client, the connection seems to get reopened as if a ...

Understanding the visibility scope in JavaScript's object-oriented programming

I have the following code snippet: function A() { this.AFunction = function() { var b = new B(); b.BFunction(); } } function B() { this.BFunction = function() { // some code $.ajax({ url: url suc ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Obtain a specific element in Puppeteer JS by utilizing the waitForSelector function to detect when its class name changes

I am faced with a situation where I need to wait for a specific element to change its classes dynamically. The challenge arises when utilizing the waitForSelector function, as it fails to work when no new element is added to the DOM. Instead, it is the &l ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

What is the process for exporting Three.js files to .stl format for use in 3D printing?

I stumbled upon a page with this link: Is it possible to convert Three.js to .stl for 3D printing? var exporter = new THREE.STLExporter(); var str = exporter.parse(scene); console.log(str); However, despite using the code provided, I am unable to export ...

Using a function as an argument within an Angular directive

Looking for a solution to pass a promise-returning function into a directive? Here's what I'm currently doing: In the parent controller, I've created a callback: $scope.myCb = function(data) { console.log(data); } Directive Scope: sco ...

Is it possible to send data to the server in node.js before the page is loaded?

Once a user has logged in, their data is stored on the client side. There are certain pages that can be viewed without requiring a user to log in... For instance, I have created a route on node.js which generates a profile page based on a URL parameter. ...

What is the best way to save functions that can be utilized in both Vue front-end and Node back-end environments at the same time?

As I dive into the world of Node/Express back-end and Vue.js front-end development, along with server-side rendering, I am faced with the need to create utility functions that can format textual strings. These functions need to be accessible and reusable b ...

Using Grails, the event listener can be triggered by a change in the

Looking for some advice on implementing a dynamic textfield element in a Grails form. I'm using the remoteFunction action to call a template, but unfortunately, the template is not being called as expected. When I switch from "g:textField" to "g:selec ...

The controller method appears to be unable to detect any parameters

I have been trying to pass an ID in the URL but my controller is not receiving that value. $("#ChangeSlideForm").on("submit", function(){ $.ajax({ type: "POST", url: base_url + "Visualiser/ChangeSlide/21", su ...

Having trouble locating an external Javascript file in a Node.JS/Express app with Jade template?

In my Node.JS/Express app, I am using the Jade template engine. The issue arises when trying to reference a server-side Javascript file named common_routines. Despite placing the Javascript file in the directory above my views directory and referencing it ...

Running two different versions of the same React-App concurrently: A step-by-step guide

I currently have a react-app that was created using create react app. There is an older branch that is approximately 1 month old, as well as a current branch. I am interested in running both branches simultaneously and making changes to the current branch ...

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

Using Node.js with the Instagram API resulted in the error message: "Failed to decode a text frame in UTF-8 format."

For my project, I am utilizing the Instagram API with the http node.js module. The API call is quite simple: getJSON : function(options, on_result, on_error) { var req = http.request(options, function(res) { var output = ''; ...