I need to sort an array of objects, which contain multiple keys whose values pertain to the index order. See example:
var array = [
{
0: .5,
1: .3,
2: .15
},
{
0: .7,
1: .25,
2: .9
},
{
0: .45,
1: .9,
2: .08
}
];
I want to sort based on the value of the keys, the key being the final index of the object within the end result of the sort. In the above example, the 2nd object in the array would be placed in index 0 because it contains the highest number for that index. Followed by the 3rd object, and finally the 1st. Current implementation:
var array = [
{
0: .5,
1: .3,
2: .15
},
{
0: .7,
1: .25,
2: .9
},
{
0: .45,
1: .9,
2: .08
}
];
var final = [null,null,null];
var largest;
for(var f=0;f<final.length;f++)
{
largest = null;
for(var a=0; a <array.length;a++)
{
var obj = array[a][f];
if(!largest || ( obj > largest[f] && final.indexOf(array[a]) == -1 ) )
{
largest = array[a];
}
}
final[f] = largest;
}
console.log(final);
Although my current implementation works, its not very optimized. This is running inside node.js, with an array of over 1500 objects. The final array does not need to contain all 1500 objects, instead its a user initiated limit (between 3 and 15). Is there any kind of way to achieve this unique sort using the native sort function, or any other known way.