Guidelines for generating a sorted indices array from a different array using TypeScript

I need help finding a way to create an ordered array of indexes from another array in TypeScript.

Let me provide some examples: imagine a function that takes an array of any length and returns another array with the indexes of the elements in ascending order:

  • Example 1: Input=(5.3, 2.4, 4.5, 6.2) > Output=(1,2,0,3).
  • Example 2: Input=(10, 11, 5, 34, 3, 7, 17) > Output=(4,2,5,0,1,6,3).

I am unable to use array.sort() as it would alter the original array.

I am struggling with this problem as my experience with JS and TS is limited (I am a Delphi programmer who is a bit rusty).

Any insights or advice would be greatly appreciated. Thank you in advance.

Answer №1

Utilize the slice() method to create a duplicate array that can be sorted without changing the original, then apply map() to generate an array containing the index of each sorted element in the original array.

const numbers = [5.3, 2.4, 4.5, 6.2],
      numbers2 = [10, 11, 5, 34, 3, 7, 17];

const getSortedIndex = (arr) => {
  return arr.slice().sort((a, b) => a - b).map(n => arr.indexOf(n))
}

console.log(JSON.stringify(getSortedIndex(numbers)));
console.log(JSON.stringify(getSortedIndex(numbers2)));

Answer №2

Is it possible to duplicate the array and then arrange the duplicate in order?

let originalArray = [3,6,1,9,2.5];
let sortedArray = [];
for(let j=0;j<originalArray.length;j++){
  sortedArray.push(originalArray[j]);
}
sortedArray.sort();
//originalArray = [3,6,1,9,2.5]
//sortedArray = [1,2.5,3,6,9]

Answer №3

It only takes two simple lines of code to achieve this:

const unsorted = [10, 20, 5, 8, 3];
const sorted = unsorted.slice().sort();

console.log(sorted);      // [3, 5, 8, 10, 20]
console.log(unsorted);    // [10, 20, 5, 8, 3]

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

Creating a dynamic HTML table in GAS with a radio button in every row poses the challenge of assigning a unique ID to each radio button in each row using a variable name

I am currently working on a Google Apps Script web application that involves a search box and a button. When the button is clicked, it dynamically loads an HTML table based on the user input from the search box. The script then retrieves data from a Google ...

react-i18next - The function call does not match any overload when the specified type is `string`

I am currently utilizing react-i18next in conjunction with React and TypeScript. Interestingly, when I attempt to load a property using a string literal and type inference, everything works seamlessly. However, once I specify the type as string, an error i ...

Unwanted elements infiltrate 2D array, causing interference

I have recently started posting on this site after being a long-time user. It has been a great resource for me. Currently, I am working on developing a memory-pool implementation, but I have encountered a peculiar issue. I have two memory pools set up, an ...

Navigating with Node.js: Understanding how to showcase the response data within a list structure

I am brand new to working with node.js and I'm looking to display the data I receive as a response on my webpage. Currently, I can see the output in my console. Is there a way to show this data on my actual page? GET Request: app.get('/bestell_ ...

Replicate the form to a new one while concealing the elements and then submit it

Initially, I was working with just one form. Now, I find myself in a situation where I need to utilize a different form which contains the same inputs. This is necessary because depending on the action taken upon submission, different processes will be tri ...

The element.find() function in Angular struggles to locate input elements nested within other elements

I have been working on a directive that has the following template (simplified): <table> <tr> <td> <input type="text"/> </td> <td> <inpu ...

Ways to showcase Firebase information with multi-tiered keys in an HTML table?

I am struggling to showcase information from a Firebase database with a multi-level key onto an HTML table using Angular. Here is the structure of the data: https://i.sstatic.net/qQ6RZ.jpg https://i.sstatic.net/PIaUZ.jpg When attempting to display using ...

Firebase's equalTo function seems to be malfunctioning

Having encountered an issue with Firebase, I am currently attempting to fetch all of my posts in JavaScript. Specifically, I am looking for posts in the correct language that are marked as "published" and sorted by their published date. In my Firebase dat ...

Angular 2 feature that allows for a single list value to be toggled with the

Currently, my form is connected to a C# API that displays a list of entries. I am trying to implement a feature where two out of three fields can be edited for each line by clicking a button that toggles between Yes and No. When the button is clicked, it s ...

Retrieve the attribute from a TypeScript union data type

Here is the structure that I am working with: export interface VendorState extends PaginationViewModel { vendors: CategoryVendorCommand[] | CategoryVendorCommand; } This is my model: export interface CategoryVendorCommand { id: string; name: str ...

Could you assist me in retrieving information from an API request?

I can't seem to pinpoint my mistake, but I know it's there. After the user provides their state and city information and submits it, a fetch request is supposed to retrieve latitude and longitude values. These values are then used in another API ...

Align a collection of images in a grid format on the center of the page with

I am trying to center a div that contains multiple 145px X 145px thumbnail images without setting a fixed width. The goal is to have as many images in each row as the browser window can fit. However, I want to keep the images left-aligned within the center ...

Can I extract JSON data from the AJAX response?

When receiving JSON data, such as in the example below, it is often necessary to separate each value into individual variables: var reviewDate ='2015-06-01T05:00:00Z' var developers ='Ankur Shah,Srikanth Vadlakonda,Tony Liu, Qiuming Jie&ap ...

If the browser is Internet Explorer, then load file [A]; otherwise, load file [B]

One of my webpages requires unique content to be loaded for different web browsers. For example: If the browser is Internet Explorer {include file="/content1.tpl"} Else if it's any other browser {include file="/content2.tpl"} {/if} Content1. ...

Scraping data from the web using R and creating interactive plots with hover text in Plotly without

I'm attempting to extract hover text content from plotly traces that have been shared online. This is a new type of scraping for me, and I'm exploring ways to accomplish this task in R without relying on selenium or phantomjs, possibly with the u ...

Personalized JQuery popup before leaving the page

Looking to display a unique jQuery dialog box with options for Yes, No, and Cancel when a user attempts to navigate away from the current page or close the window. The default browser dialog confirmation is displayed on the beforeload event, but we are tr ...

Adding additional objects to an object overwrites any existing appended data

Check out this pen to see what I'm working on and the issue I'm facing: http://codepen.io/Irish1/pen/lbjdw I've been working on a program that involves adding a week object, where I can input the name of the week along with a description. H ...

The feature to Select/DeSelect All does not function properly when dealing with individual records

Here's the JavaScript code I'm working with: if (document.forms[0].Check_All.value=="Select All") { for (i = 0; i < chk.length; i++) { chk[i].checked = true; document.forms[0].Check_All.value = "DeSel ...

A guide on assigning a state variable to a dynamically generated component within a React application

I need to display user data from an array and have a button for each watchlist that deletes it. Although the backend is set up with a function deleteWatchlist, I am facing an issue in setting the state of the watchlistName for each watchlist after mapping ...

Creating input fields dynamically within Yii2 framework

I'm currently facing a challenge with forms in Yii2. My objective is to design a form that includes three dropdown menus, inquiring about the user's preferred time(s) during the week. The first menu will focus on selecting days of the week, while ...