lbennet
lbennet

Reputation: 1103

Rearrange javascript object - keys using .sort() are not kept as on the array which is being sorted

var tagged={"tagged":[
{"positionX":11,"positionY":13},
{"positionX":12,"positionY":18},
{"positionX":10,"positionY":20}
]};

So I have this object,

I need to reconstruct it so that it ends up looking as follows:

var tagged={"tagged":[
{"positionX":10,"positionY":20},
{"positionX":11,"positionY":13},
{"positionX":12,"positionY":18}
]};

Sorted by positionX ASC.

I have tried:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
        var tagged={"tagged":[
        {"positionX":11,"positionY":13},
        {"positionX":12,"positionY":18},
        {"positionX":10,"positionY":20}
        ]};

        tagged=tagged.tagged;

        var newtagged=new Array();
        for (var i = 0; i < tagged.length; i++) {
        newtagged[i]=tagged[i].positionX;   
        }

        var sorted=newtagged.sort(function(a,b){return a-b});

        $(sorted).each(function(k,v){   
        alert(v);
        });
</script>

There indeed is a successful sort but the keys are incorrect in the new "sorted" array.

So I am unable to retrieve all the correct values in the original object based on the original reading of the keys, I mean, without the original key of sorted I don't know to what belongs the sorted "positionX", that way I am unable to retrieve its corresponding positionY in array tagged. .sort(function(){}); assigns new keys to sorted array.

Upvotes: 1

Views: 366

Answers (1)

Rune FS
Rune FS

Reputation: 21752

If I understand your question correctly you wish to sort tagged according to the value of positionX. If that's the case you can simply pass a function to sort that compares the attributes.

var sorted=tagged.sort(function(a,b){return a.positionX-b.positionX});

Upvotes: 3

Related Questions