Home > Blockchain >  Typescript array from map sorted by value?
Typescript array from map sorted by value?

Time:09-14

I am trying convert a map into a sorted array. There are millions of solutions around, all of which result in one of many many many different errors.

I want to sort this:

public midiCcs: Map<string, ControllerInfo> = new Map<string, ControllerInfo>();

into an array of ControllerInfo ordered by ccMsb:

export class ControllerInfo {
    public name: string = "unassigned";
    public ccMsb: number = 0;
    public ccLsb: number = 0;
    public max: number = 127;
    public min: number = 0;

    constructor(jsonObject: any) {
        this.name = jsonObject.name;
        this.ccMsb = jsonObject.ccMsb;
        this.ccLsb = jsonObject.ccLsb;
        this.max = jsonObject.max;
        this.min = jsonObject.min;
    }

    public toString = () => {
        return `ControllerInfo ${this.name} ${this.min} to ${this.max} ccMsb ${this.ccMsb} ccLsb ${this.ccLsb}`
    }
}

Would greatly appreciated a way out of this minefield.

CodePudding user response:

You can try this approach with sort() (to sort Map by keys) and values() (to get values from Map).

class ControllerInfo {
    public name: string = "unassigned";
    public ccMsb: number = 0;
    public ccLsb: number = 0;
    public max: number = 127;
    public min: number = 0;

    constructor(jsonObject: any) {
        this.name = jsonObject.name;
        this.ccMsb = jsonObject.ccMsb;
        this.ccLsb = jsonObject.ccLsb;
        this.max = jsonObject.max;
        this.min = jsonObject.min;
    }

    public toString = () => {
        return `ControllerInfo ${this.name} ${this.min} to ${this.max} ccMsb ${this.ccMsb} ccLsb ${this.ccLsb}`
    }
}

const midiCcs: Map<string, ControllerInfo> = new Map<string, ControllerInfo>([
    ["C", new ControllerInfo({ name: "C" })],
    ["A", new ControllerInfo({ name: "A" })],
    ["B", new ControllerInfo({ name: "B" })]
]);

const notSortedArray: ControllerInfo[] = Array.from(midiCcs.values());

console.log(notSortedArray)

//shorter version in short()
//const sortedArray: ControllerInfo[] = Array.from(new Map(Array.from(midiCcs).sort()).values());

const sortedArray: ControllerInfo[] = Array.from(new Map(Array.from(midiCcs).sort(([key1], [key2]) => key1.localeCompare(key2))).values());

console.log(sortedArray)

Playground

CodePudding user response:

I'm assuming you want to keep the string label. It could be something like this:

Array.from(midiCcs)
    .sort(([label1, item1], [label2, item2]) => item1.ccMsb - item2.ccMsb);
  • Related