Sorting an array of numbers in TypeScript using the array sort function

Looking to organize an array based on ID, comparing it with another array of numbers

    var items:[] = [{
    item:{id:1},item:{id:2},item:{id:3},item:{id:4}
    }]

var sorted:[] = [1,3,2,4];

Output:

var items:[] = [{
    item:{id:1},item:{id:3},item:{id:2},item:{id:4}
    }]

Answer №1

The array of items you have is currently incorrect as it only contains one item.

To correct this issue, here is a method you can use to sort them:

const items = [{id: 1}, {id: 2}, {id: 3}, {id: 4}];
const sort = [1, 3, 2, 4];
const sorted = sort.map(value => items.find(item => item.id === value));
console.log(sorted);

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

System CSS modules do not work correctly with Reactjs, CRA, TS, and Carco when using Less

Issues have arisen with the CSS module system in my project. Below are snippets from various code files and configurations: react-app-env.d.ts, craco.config.js, CircleButtonWithMessage.module.less, CircleButtonWithMessage.tsx, as described below: //react-a ...

Angular 6 is showcasing dates in a quirky manner

In my Angular app, users can enter comments. The comments are displayed automatically with the date they were added. However, there is an odd behavior that I've noticed: When a user enters a comment, the time displayed is incorrect. (Check the ...

What is the best way to implement "computeIfAbsent" or "getOrElseUpdate" functionality for a Map in JavaScript?

If we assume that m represents a Map<number, V> for a certain type V k is a number, how can we create an expression that can either retrieve an existing V for the key k, or generate a new v: V, insert it into the map for the key k, and result in v ...

When attempting to select dates from the picker options, the array is found to be devoid of any entries

My challenge lies in working with an array of dates retrieved from the server to determine which dates should be disabled on the datepicker. getStaffAvailability(){ let x = this; this.$http.get(this.weeklyAvailabilityUrl + "GetAv ...

What is the best way to extract a specific value from a JSON object?

I'm currently working on building a marketplace using Angular. The main marketplace page is already set up and populated with data from a remote JSON file created with mockapi. However, I've encountered an issue when trying to display a single ra ...

TypeScript encountered an error with code TS2305, stating that the module "constants" does not have any exported members

My Vite + React + TypeScript application has the following structure: src constants a.ts b.ts index.ts components Comp.tsx tsconfig file with "baseUrl": "src" The content of a.ts is as follows: export const ARRAY = ...

Tips for accessing the return value from a method outside of its containing function

Having recently started using Angular, I'm encountering an issue with retrieving a return value from a function that I have implemented within another one. private validateKeyterm(): boolean { const val = this.form.value.term; if ...

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

Is the return value a result of destructuring?

function display(): (number, string) { return {1,'my'} } The code above is displaying an error. I was hoping to use const {num, my} = print(). How can I correctly specify the return type? ...

Issues encountered when saving and fetching data using AsyncStorage

My situation involves a storage object structured like this: import AsyncStorage from "react-native"; const deviceStorage = { async saveItem(key, value) { try { await AsyncStorage.setItem(key, value); } catch (error) { ...

AppProps in Next.js - Ensure that you have the correct loader set up to handle this specific file type as there are currently no loaders configured for processing it

I've encountered an issue while working on a Next.JS 13.5.6 application in development mode. When I try to connect to the site, I receive an error message. However, everything works fine when I switch to production mode after building and starting the ...

Typescript: Transforming generic types into concrete types

I am utilizing a Generic type type GenericType = { [key: string]: { prop1: string, prop2?: string, prop3?: number, }, }; The purpose of the Generic type is to assist in constructing / validating a new object that I have created. const NewO ...

Does this Spread Operator Usage Check Out?

Upon reviewing Angular's API documentation, I came across the declaration for the clone() method in HttpRequest as follows: clone(update: { headers?: HttpHeaders; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" ...

Combining keys from an array of objects into a single array categorized by key names

When working with an array of objects, I need to filter and extract all the keys. One challenge I face is when there are nested objects, I want to concatenate the key names to represent the nested structure. For example: const data = [ id: 5, name: "S ...

Exploring the power of async/await and promise in TypeScript

I'm puzzled as to why the return type string in this method is showing up as a red error: exportPageAsText(pageNumber: number): string { (async () => { const text = await this.pdfViewerService.getPageAsText(pageNumber); ...

Ensuring Safe Definition of HTMLCollectionOf Elements in TypeScript with React

I'm currently working on creating a d3 line chart using react and typescript, and I'm using https://bl.ocks.org/larsenmtl/e3b8b7c2ca4787f77d78f58d41c3da91 as a reference for implementing the mouse over functionality. During one step of the proce ...

What is the best way to convert a `readonly string[]` to a regular `string[]`?

My data setup is as follows (I am not declaring it as an enum because it is used in both TypeScript server code and non-TypeScript client code): import { enumType } from 'nexus'; export const TYPE_ENUM = Object.freeze({ H: 'H', S: ...

Updating the displayed data of an angular2-highcharts chart

I am facing an issue with rendering an empty chart initially and then updating it with data. The charts are rendered when the component is initialized and added through a list of chart options. Although the empty chart is successfully rendered, I am strugg ...

get a duplicate of an object

Is this the proper method for creating a duplicate of an object? class ObjectWrapper { private _obj; /*** * Copy object passed as argument to this._obj */ constructor (_obj: Object) { this._obj = _obj; } /** Return copy of this._ ...

Steps for wrapping a class with a higher order component

Is it feasible to encapsulate a class component within a higher order component (HOC) that is also a class? import React, { Component } from "react"; import { View } from "react-native"; import { Toast } from "react-native-easy-toast"; const withToast = ...