Kode_12 - 8 months ago 26

Javascript Question

I have an array of objects.

In each object, I'm targeting a property called "myLevel". The values for this property vary in the following string syntax:

`[`

{myLevel : 'CAT I #4'},

{myLevel : 'CAT I #6'},

{myLevel : 'CAT I #2'},

{myLevel : 'CAT II #15'},

{myLevel : 'CAT III #1'},

{myLevel : 'CAT II #7'},

]

How can I sort the array so that the objects are rearranged in ascending order like so:

`[`

{myLevel : 'CAT I #2'},

{myLevel : 'CAT I #4'},

{myLevel : 'CAT I #6'},

{myLevel : 'CAT II #7'},

{myLevel : 'CAT II #15'},

{myLevel : 'CAT III #1'}

]

Answer

Use RegEx to match the parts, then check those parts individually

```
var arr = [
{myLevel : "CAT I #4"},
{myLevel : "CAT I #6"},
{myLevel : "CAT I #2"},
{myLevel : "CAT II #15"},
{myLevel : "CAT III #1"},
{myLevel : "CAT II #7"}
];
var sorted = arr.sort(function(a,b){
var left = a.myLevel.match(/CAT (I+) #([0-9]+)/);
var right = b.myLevel.match(/CAT (I+) #([0-9]+)/);
if(left[1].length==right[1].length){
return left[2]-right[2];
}else return left[1].length-right[1].length;
});
```

The `match`

returns

```
[0] whole matched string
[1] all the `I`'s
[2] the number after the #
```

The first `if`

is to check if the `I`

count is the same, if it is we need to check by the number.

If we need to check by the number, we just need to return the difference between them.

If we don't need to check by the number we just need to return the difference between the amount of `I`

's