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.