'How to sort an array based off an array of indexes that are in order?
I'm trying to sort an array of words based off an array of indexes. Here is the array of words:
const animalArray = ['Wolf', 'Cat', 'Dog', 'Rabbit', 'Random']
Here is an Array of indexes that i have been given that correlate to the order the animal array above needs to be in:
const indexArray = [ 3, 0, 1, 2 ]
So in indexArray, we start off with index 3. This correlates to 'Rabbit' in the animalsArray. 3 is at index 0 in the indexArray so we should should move 'Rabbit' to index 0. We should keep doing this until we reach the end of the array. Any extras should be added to the end of the array. So once the function runs, we should get the following result:
sortArray(animalArray, indexArray); // ['Rabbit', 'Wolf, 'Cat', 'Dog', 'Random']
I have figured out the first part (create the index array). However, i don't know how to get them in the correct order. How can i put the animalsArray in the correct order?
EDIT:
I oversimplified this and ended up not asking the question correctly.
We should actually pass 3 params to the sortArray, the third being an object that gets sorted:
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'
}
]
It should sort like so:
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'
}
]
*/
Solution 1:[1]
var sortedAnimalArray = []
for(var i = 0; i < indexArray.length; i++ {
sortedAnimalArray[i] = animalArray[indexArray[i]]
}
Solution 2:[2]
Map the indexArray to access each element at the index, then go through the animals to identify holes.
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);
Solution 3:[3]
You can use promise .
const myPromise = new Promise((resolve, reject) => {
const animalArray = ['Wolf', 'Cat', 'Dog', 'Rabbit', 'Random']
const indexArray = [ 3, 0, 1, 2 ]
let pushArray = []
var resolveValue = 0
for(var i=0;i<indexArray.length;i++){
pushArray.push(animalArray[indexArray[i]])
resolveValue ++
}
console.log(pushArray)
if(resolveValue == indexArray.length){
resolve('Promise is resolved successfully.');
}
});
Solution 4:[4]
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 animalArray = ['Wolf', 'Cat', 'Dog', 'Rabbit', 'Random']
const indexArray = [ 3, 0, 1, 2 ]
const animalMap = {}
for (let i = 0; i < animalArray.length; i++) {
animalMap[animalArray[i]] = indexArray[i]
}
for (let i = 0; i < animalObjects.length; i++) {
const sentence = animalObjects[i].name
for (const word of sentence.split(" ")) {
if (animalMap[word] !== undefined) {
animalObjects[i].position = animalMap[word]
break
}
}
if (animalObjects[i].position === undefined) {
animalObjects[i].position = indexArray.length
}
}
animalObjects.sort((a, b) => a.position - b.position)
console.log(animalObjects)
We create a map of animal keyword to its supposed index, animalMap. For each element in animalObjects we search for an animal keyword, if we find one we assign the corresponding index to the animalObject. If we don't find any, we assume it's a random object and should come at the end. Then we sort based on these indices.
Note that if there are 2 or more animal keywords in one animal object, this algorithm takes the first and ignores the rest. In addition, this algorithm is capable of sorting animalObjects where the are multiple elements with the same animal keyword (like 2 elements with a name property that contain Dog).
This can of course be written in a much more javascriptesque way, using map, etc. But I thought it's important to get the algorithm right and well understood first.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yannick Y |
| Solution 2 | CertainPerformance |
| Solution 3 | Khandker Ashik Mahmud |
| Solution 4 | user1984 |
