Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Ordenar matriz de objetos según la posición del valor en otra matriz de cadenas

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

 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.

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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 }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!