-1

I have a criticality array and I want to sort by criticality, something like this:

let criticalityTypes = ['CRITICALITY_LOW', 'CRITICALITY_HIGH', 'CRITICALITY_MEDIUM'];

I get this order randomly, sometimes ** CRITICALITY_LOW ** comes in position 1 of the matrix ie either position 2, or 'CRITICALITY_MEDIUM' in 0 position,

What I want to do is order in the following order, regardless of the order that comes to me, sometimes I have just one criticality, or two:

['CRITICALITY_HIGH', 'CRITICALITY_MEDIUM', 'CRITICALITY_LOW'];

I tried to use sort function to order what I've done so far is this:

return criticalityTypes.sort((a, b) => {
    if (a < b) return -1;
    if (a > b) return 1;
});

But without success, any help?

Jefferson Bruchado
  • 888
  • 2
  • 14
  • 33

3 Answers3

4

You could take an object with the wanted order and sort by the delta of the values.

var criticalityTypes = ['CRITICALITY_LOW', 'CRITICALITY_HIGH', 'CRITICALITY_MEDIUM'],
    order = { CRITICALITY_HIGH: 1, CRITICALITY_MEDIUM: 2, CRITICALITY_LOW: 3 };

criticalityTypes.sort((a, b) => order[a] - order[b]);

console.log(criticalityTypes);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Just another way:

let criticalityTypes = ['CRITICALITY_LOW', 'CRITICALITY_HIGH', 'CRITICALITY_MEDIUM'];
let orderedItems = [];
let desiredOrder = ['CRITICALITY_HIGH', 'CRITICALITY_MEDIUM', 'CRITICALITY_LOW'];

 for (var i = 0; i < desiredOrder.length; i++) {
    if (criticalityTypes.indexOf(desiredOrder[i]) > -1) {
        orderedItems.push(desiredOrder[i]);
    }
 }

 console.log(orderedItems);
StepUp
  • 36,391
  • 15
  • 88
  • 148
-1

The problem here is that you as the consumer of the api, do not have any clue what an "order" means for this items, as they are not "quantized", they are ideas, not an integer that you could call 'order' so you know what is what, the string is just for the display anyway.

Since you can not change the api, BUT they are always only these 3 and you always want them in the same order, you can mock your current call, put this as a 'placeholder' comparer so that you mock the calls to this function, until someones gives you something that you can use numericaly to determine an order, 'ascending' or 'descending' requires something quantized to have a meaning.

function criticalityTypes(a,b){
    return ['CRITICALITY_HIGH', 'CRITICALITY_MEDIUM', 'CRITICALITY_LOW'];
}
MKougiouris
  • 2,821
  • 1
  • 16
  • 19
  • 1
    The parameters aren't needed. – Blackhole Jul 30 '19 at 19:37
  • Either the api provider will return to you keys with an id and a string value, or you will just return them directly if indeed "there is always only theese 3 and i need them always returned in this way". – MKougiouris Jul 30 '19 at 19:40
  • This doesn't answer the question, and it's based on incorrect assumptions. There are *not* "always only these 3". – user229044 Aug 23 '19 at 16:24