0

I have an array like this:

var data = ['High', 'Low', 'Medium'];

This data array is created dynamically. So, it may have all 3 values or only 2 values or 1 value.

Regardless of the values in the array, I would like the array to be sorted in this fashion:

 var sortedArray = ['High', 'Medium', 'Low']

I have tried something like this:

var sortedArray = []
for(var 0;i<data.length;i++)
{
   if(data[i] = 'High')
    {
       sortedArray.push('High');
    }
   else if(data[i] = 'Medium')
    {
       sortedArray.push('Medium');
    }
    else if(data[i] = 'Low')
    {
       sortedArray.push('Low');
    }
}

How can we achieve that?

Jake
  • 25,479
  • 31
  • 107
  • 168

2 Answers2

1

You can start with the complete array already sorted, and filter out the elements that aren't in data.

var data = ['Low', 'High'];

var sortedArray = ['High', 'Medium', 'Low'].filter( el => data.includes( el ) );

console.log( sortedArray );
Paul
  • 139,544
  • 27
  • 275
  • 264
0

var data = ['High', 'Low', 'Medium'];

// create a dictionary to map each possible value
var map = {High: 3, Medium: 2, Low: 1, Default:0 };

// then sort

var sorted = data.sort((a,b)=>(map[a]||map.Default)>(map[b]||map.Default)?-1:1);

console.log(sorted);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116