Creating a custom sorting function in Typescript for arrays using a comparator

Looking to implement a custom sorting method for an array that consistently arrives in varying orders:

[{code: 'A'},{code: 'O'},{code: 'I'}],  [{code: 'O'},{code: 'A'},{code: 'I'}], ...

The desired order is

[{code: 'A'},{code: 'O'},{code: 'I'}]
.

export function customSort(arrayToSort): Array {
  if (!arrayToSort || arrayToSort.length < 1) {
    return [];
  }
  const sorted = new Map();
  const sorting = ['A', 'O', 'I'];

  for (let i = 0; i < sorting.length; ++i) {
    sorted.set(sorting[i], i);
  }
  return arrayToSort.sort((a, b) => sorted.get(a.code) - sorted.get(b.code));
}

An attempt was made by creating a map with the desired sorting configuration, setting keys as 'A' and values as numbers to facilitate sorting. However, an error occurred:

core.js:15724 ERROR TypeError: Cannot assign to read only property '0' of object '[object Array]'
. At this point, further solutions are needed.

Answer №1

It seems like you're aiming too high.

Just stick to using an array for sorting and trust the index of the items in it.

const data = [
  { code: 'O' },
  { code: 'A' },
  { code: 'I' },
];

const order = ['A', 'O', 'I'];

const sorted = data.sort((a, b) => order.indexOf(a.code) - order.indexOf(b.code));

console.log(sorted);

Answer №2

The data originates from the redux store and is unchangeable, thus I addressed it by applying a slice() function prior to executing sort(). However, I must admit that @Maryannah's approach far surpasses mine.

Answer №3

When I ran your code, it didn't give me a runtime error but rather a build error related to type declaration. It seems that an Array requires a specific type, even if it's any. To fix this issue, I had to modify the function declaration like so:

export function someSort(arrayToSort): Array<any> {

After making this change, the code was able to build, run, and generate the expected output.

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

Error 91 occurs at runtime while trying to assign an array to a table that only has one

Initially, I set a table data body range to an array called arr = tbl.DataBodyRange, which functions correctly. Reassigning the array back to the table with tbl.DataBodyRange = arr works for arrays containing more than one row. However, when the array on ...

The parameter "file" needs to be a string data type, but npm run deploy to gh-pages received an undefined data type instead

I encountered an error while attempting to deploy a react application to gh-pages. Despite having successfully done it in the past, this is the first time I am facing this specific issue. The error message reads: The "file" argument must be of type string ...

Personalize Angular material mattooltip and style information for display in tooltip

I need assistance displaying data in a tooltip in JSON format similar to the image provided. Although I can load the data in the tooltip, it does not appear formatted like the attached picture. <ng-container matColumnDef="Alert"> &l ...

Tips for successfully including a positive sign character in string values within JSON in the URL's hash fragment

I am facing an issue with my JS (Angular) app where I load parameters from the URL fragment after the # sign. These parameters contain JSON objects, like this example: ...#filters={"Course":["ST_12.+13.12.2016 [Basel]"]} The aim is to open a data-grid an ...

Displaying zeros in an array declared on the heap in C++ programming language

I am working on a program that allows users to input numbers into an array and then display them. However, I'm encountering an issue where if the size of my array is set to 100, the output includes unwanted zeros at the end. Here's what I want t ...

Tips for concealing .js and .map files in WebStorm during your work on an Angular 2 TypeScript project

After attempting to include the extensions in the .gitignore file, the outcome is shown in the following image: https://i.sstatic.net/0K6x5.png Unfortunately, the files are still not fully concealed. ...

What could be causing JavaScript to fail in recognizing my constructor?

I encountered a problem where the script fails to recognize the constructor in the class and incorrectly assumes that I am calling all the other functions as constructors. class Articles { constructor(dbName = ':memory:') { return(asy ...

Deduct a digit from a variable

My goal is to decrease the value of revlength each time the loop runs. For example, if there are 2 posts by 'A Google user', then subtract 2 from revlength. This is my attempted solution: var revlength = place.reviews.length; if (place.reviews[ ...

Extracting repeated information from a form_for select box using jQuery looped through

How can I duplicate the output of a Rails loop and display it in a different section of the webpage? This is the ERB code I am currently using: <%= form_for @order do |f|%> <div class="col-xs-6"> <%= f.fields_for :units, @orde ...

"Exploring the world of arrays and looping in

Can someone assist me with this issue? I am currently stuck in JS Arrays & Loops and I can't understand why it's not returning "0" when the function is empty. function sumArray (numbers) { // your code var numbers = [1, 2, 3, 4]; if (nu ...

Array elements will now be refreshed with latest data from the table

Here is a breakdown of prices for various items in a table: |----------------------------| | ItemID (INT) | Price (INT) | |--------------|-------------| | 1 | 50 | |--------------|-------------| | 2 | 36 | |-------- ...

React - modifying parent's Redux property

After connecting my Container to redux using the following: const mapStateToProps = ({ MyReducer }) => ({ myProp: MyReducer.myProp }); I am wondering if it is possible to manually set the value of myProp from the parent component (bypassing redux) ...

Concatenating Arrays in nodeJS

Here's a code snippet that deals with arrays: const array = [ "apple", "banana", "cherry" ]; I'm trying to create a multiline string like this: const foo = " apple banana cherry "; Is there a way for me to begin a new line with each it ...

What is the functionality of props when utilized by a component that is defined within another component?

I am currently working on developing a multi-stage form using React. The component structure I have set up looks like this: MainForm SubForm1 SubForm2 SubForm3 The MainForm component includes states named step and formData, along with methods such as ...

Ensure that the <TabPanel> content occupies the entire width and height of its parent container

Currently, I am working with React and material-ui. Specifically, I am utilizing an appbar with tabs and my goal is to have the content of each tab expand to full width and height when selected. If you'd like to see an example, check out this sandbox ...

A sticky sidebar in HTML that is confined to a specific div element

I'm working on creating an HTML sidebar that is constrained to the size of a div (not full-screen like typical sidebars) and also sticky. This means that when the height of the div exceeds the screen's height, the sidebar should stick to the scre ...

Express server consistently receives JSON requests that contain no data in the request body

Currently, I am in the process of developing a small server and website using Express. At this point, my goal is to send a POST request to my Express server with basic credentials encoded as JSON. The issue I am facing is that no matter what I attempt, th ...

I am currently attempting to find a color picker element within a parent class using Cypress CSS Locator. While I am able to reach the parent element, I am unsure of the correct method to target the

My user interface has a list of elements displayed in 2 columns. The first column shows the name of the item, such as Manager, Operator, and the list is expected to grow. The second column consists of a color picker element where you can choose a color. I ...

What is the process for invoking a functional component within a class-based component using the onClick event?

I am trying to display my functional component in a class-based component, but it is not working as expected. I have created a SimpleTable component which is function-based and displays a table with some values. However, I want to show this table only wh ...

Is it possible to retrieve the value of this input field within a function call in HTML?

When working with an HTML input field, I encountered the need to limit manual input to 100. Although I already had minimum and maximum values set up for spinner functionality (up and down arrows), I wanted to create a reusable function instead of using inl ...