0

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.

0

2 Answers 2

1

This solution features a while loop and a for loop with a decreasing data set for every found largest item.

var array = [{ 0: .5, 1: .3, 2: .15 }, { 0: .7, 1: .25, 2: .9 }, { 0: .45, 1: .9, 2: .08 }],
    final = [],
    largest, a, f = 0;

while (array.length) {
    largest = 0;
    for (a = 1; a < array.length; a++) {
        if (array[a][f] > array[largest][f]) {
            largest = a;
        }
    }
    final.push(array.splice(largest, 1));
    f++;
}

document.write('<pre>' + JSON.stringify(final, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

Comments

1

As @usandfriends points out, you should be using a custom sorter implentation. In your case, though, you want to dynamically create one before using it so that your custom index can be made the sorting key.

For example:

var createCustomSorter = function (index) {
    return function (a, b) {
        return a[index] > b[index] ? 1 : -1;
    };
};

var customSorter = createCustomSorter(1)

console.log(array.sort(customSorter));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.