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

174
Views
¿Cómo ordenar una matriz basada en una matriz de índices que están en orden?

Estoy tratando de ordenar una serie de palabras en función de una serie de índices. Aquí está la matriz de palabras:

 const animalArray = ['Wolf', 'Cat', 'Dog', 'Rabbit', 'Random']

Aquí hay una matriz de índices que me han dado que se correlacionan con el orden en que debe estar la matriz de animales anterior:

 const indexArray = [ 3, 0, 1, 2 ]

Entonces, en indexArray , comenzamos con el índice 3. Esto se correlaciona con 'Rabbit' en animalsArray . 3 está en el índice 0 en indexArray , por lo que deberíamos mover 'Rabbit' al índice 0. Deberíamos seguir haciendo esto hasta llegar al final de la matriz. Cualquier extra debe agregarse al final de la matriz. Entonces, una vez que se ejecuta la función, deberíamos obtener el siguiente resultado:

 sortArray(animalArray, indexArray); // ['Rabbit', 'Wolf, 'Cat', 'Dog', 'Random']

He descubierto la primera parte (crear la matriz de índice). Sin embargo, no sé cómo ponerlos en el orden correcto. ¿Cómo puedo poner los animalsArray en el orden correcto?

EDITAR:

Simplifiqué demasiado esto y terminé sin hacer la pregunta correctamente.

En realidad, deberíamos pasar 3 parámetros a sortArray, siendo el tercero un objeto que se ordena:

 const animalObjects = [ { name: 'the Wolf goes to the beach' }, { name: 'the Cat climbs a tree' }, { name: 'the Dog runs around' }, { name: 'the Rabbit burrows' }, { name: 'Random extra object that should be at the end' } ]

Debería ordenarse así:

 sortArray(animalArray, indexArray, animalObjects); /* returns - [ { name: 'the Rabbit burrows' }, { name: 'the Wolf goes to the beach' }, { name: 'the Cat climbs a tree' }, { name: 'the Dog runs around' }, { name: 'Random extra object that should be at the end' } ] */
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

var sortedAnimalArray = [] for(var i = 0; i < indexArray.length; i++ { sortedAnimalArray[i] = animalArray[indexArray[i]] }
about 4 years ago · Juan Pablo Isaza Report

0

Asigne indexArray para acceder a cada elemento en el índice, luego revise los animales para identificar los agujeros.

 const animalArray = ['Wolf', 'Cat', 'Dog', 'Rabbit', 'Random']; const indexArray = [ 3, 0, 1, 2 ]; const indicies = new Set(indexArray); const results = indexArray .map(index => animalArray[index]) .concat( animalArray.filter((_, index) => !indicies.has(index)) ); console.log(results);

about 4 years ago · Juan Pablo Isaza Report

0

Para que sea sencillo.

  • Use Array.map() para iterar indexArray
  • Compare los elementos en ambos arreglos usando Array.indexOf() e inserte el elemento restante en un arreglo de resultados.

Prueba esto :

 const animalObjects = [{ name: 'the Wolf goes to the beach' }, { name: 'the Cat climbs a tree' }, { name: 'the Dog runs around' }, { name: 'the Rabbit burrows' }, { name: 'Random extra object that should be at the end' }]; const indexArray = [ 3, 0, 1, 2 ]; const newArray = indexArray.map((item) => animalObjects[item]); animalObjects.forEach((animal) => { if (newArray.indexOf(animal) === -1) { newArray.push(animal) } }) console.log(newArray);

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!