Sort Array of Objects based on position of value in another Array of Strings

Jammy

I have one array:

const CORRECT_ORDER = ['Animal','Plant','Sand','Grass'];

Then I have another array of Objects:

const UNSORTED = [{Type: 'Grass', Value: 'Wet'}, {Type: 'Sand', Value: 'Dry'}, {Type: 'Animal', Value: 'Dog'}];

I want to sort the UNSORTED array so that the Animal type comes first, followed by Plant then Sand and Grass.

If the CORRECT_ORDER array changes order I should be able to resort the UNSORTED array to match the new order.

It is safe to assume that no Types (Grass, Sand, Plant, Animal) will repeat and that type will only show up once in the unsorted array, if at all.


I have tried something like the following: PSUEDO CODE:

const SORTED = [];
UNSORTED.ForEach(value){
 const positionIndex = CORRECT_ORDER.indexOf(value.Type);

 if(positionIndex > SORTED.length){
   //Push at end
   SORTED.push(value);
 } else {
   //Push at index
   SORTED.splice(positionIndex, 0, value);
 }
}

return SORTED;

Unfortunately this isn't foolproof and it often sorts things incorrectly, especially on datasets that are a big larger.

Maik Lowrey

You can loop the correct_order array and filter the unsorted array by using the js filter function. If filter match push to an new array.

const UNSORTED = [{Type: 'Grass', Value: 'Wet'}, {Type: 'Sand', Value: 'Dry'}, {Type: 'Animal', Value: 'Dog'}];

const CORRECT_ORDER = ['Animal','Plant','Sand','Grass'];

let sorted = []
CORRECT_ORDER.forEach(k => {
  let n = UNSORTED.filter(obj => {
    return obj.Type === k
  })
  if (n.length > 0) {
    sorted.push(n);  
  }
  
})

console.log(sorted);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324236094&siteId=291194637