Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    May 2007
    Posts
    9
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Smile Sort objects by property

    Hello, I have the following object:

    Code:
    		var layers = {			
    			photo1 : {
    				index : 1,
    				xPos : 63,
    				yPos : 48,
    				angle : 0
    			},
    			background : {
    				index : 0,
    				xPos : 278,
    				yPos : 163,
    				angle : 0
    			}
    		}
    How can I sort the objects by the index property?

    Code:
    for(var layer in layers.sort(???))
    {
    }
    Thx Very Much!

  • #2
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,037
    Thanks
    0
    Thanked 250 Times in 246 Posts
    Put each object in an array then you can use array's sort() method.

    Code:
    var arr = [];
    for (var i in layers) {
       arr.push(layers[i]);
    }
    arr.sort(function(a, b){
        return a.index - b.index;
    });
    //test it
    for (var i in arr){
       alert(arr[i].index);
    }

  • Users who have thanked glenngv for this post:

    grogo21 (04-03-2012)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •