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' } ] */var sortedAnimalArray = [] for(var i = 0; i < indexArray.length; i++ { sortedAnimalArray[i] = animalArray[indexArray[i]] }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);Para que sea sencillo.
indexArrayPrueba 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);