Tengo una matriz:
const CORRECT_ORDER = ['Animal','Plant','Sand','Grass'];Luego tengo otra matriz de objetos:
const UNSORTED = [{Type: 'Grass', Value: 'Wet'}, {Type: 'Sand', Value: 'Dry'}, {Type: 'Animal', Value: 'Dog'}];Quiero ordenar la matriz SIN CLASIFICAR para que el tipo Animal sea lo primero, seguido de Planta, luego Arena y Hierba.
Si la matriz CORRECT_ORDER cambia de orden, debería poder recurrir a la matriz UNSORTED para que coincida con el nuevo orden.
Es seguro asumir que ningún tipo (hierba, arena, planta, animal) se repetirá y que ese tipo solo aparecerá una vez en la matriz sin clasificar, si es que aparece.
He intentado algo como lo siguiente: CÓDIGO PSUEDO:
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;Desafortunadamente, esto no es infalible y, a menudo, ordena las cosas incorrectamente, especialmente en conjuntos de datos que son mucho más grandes.
const CORRECT_ORDER = ['Animal','Plant','Sand','Grass']; const UNSORTED = [{Type: 'Grass', Value: 'Wet'}, {Type: 'Sand', Value: 'Dry'}, {Type: 'Animal', Value: 'Dog'}]; function sort_objects(order, unsortedArray){ let newArray = Array(); for(i = 0; i < order.length; i++){ for(j = 0; j < unsortedArray.length; j++){ if(unsortedArray[j].Type == order[i]){ newArray.push(unsortedArray[j]); break; } } } return newArray } console.log(sort_objects(CORRECT_ORDER, UNSORTED))esto podría funcionar, pero se puede hacer más eficiente.
Puede hacer un bucle en la matriz correct_order y filtrar la matriz no ordenada utilizando la función de filtro js. Si el filtro coincide, empuje a una nueva matriz.
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);Prueba esto
function sort() { const map = {} CORRECT_ORDER.map((type, i) => (map[type] = i)) const sortedArr = UNSORTED.sort((a, b) => map[a.Type] - map[b.Type]) return sortedArr }