问题描述:

I have an enum of different Steps

 export enum StepCategory {

START = 0,

POSITION_1 = 1,

TRANSPORT = 2,

RECEIVER = 3,

END = 4,

NO_STEP_MATCH = 5

}

This will later result in an array, where for every Step I have an object. The Problem is I won't load all the information at once, so i can'tdo a simple for-loop and push each item chronogically. I could be that I first load the value for Step 4, so my array would be:

var array = [{"END" , "POSITIVE"}]

Afterwards I would get the Info for Step 2, then I would have:

var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]

But this is not sorted.

What should I do? Should I declare an array of 6 undefined values

var array = [undefined, undefined, undefined, undefined, undefined, undefined]

This way I wouldn't need any sorting-algorithm after each Update, and can just push the value at the right position.

Just some small Info: I use AngularJS 1, Typescript and Lodash

网友答案:

In plain Javascript, you could sort it with an object and the assigned values of the key.

var StepCategory = { START: 0, POSITION_1: 1, TRANSPORT: 2, RECEIVER: 3, END: 4,  NO_STEP_MATCH: 5 },
    array = [["END", "POSITIVE"], ["TRANSPORT", "POSITIVE"]];

array.sort(function (a, b) {
    return StepCategory[a[0]] - StepCategory[b[0]];
});

console.log(array)
网友答案:

First of all, this is - as someone mentioned in the comments - not syntactically correct:

var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]

I assume that this was just a typo writing this question. Additionally if you actually use the enum in your array as key and just left it out for demonstration purposes, I would expect your array of objects to look something like this:

var array = [{StepCategory.END: "POSITIVE"}, {StepCategory.TRANSPORT: "POSITIVE"}]

In order to sort this with LoDash you could use something like this:

var sortedArray = _.sortBy(array, i => Object.keys(i)[0]);

This sorts your array by the value of the first key of each object which refers to your enum value.

相关阅读:
Top