Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  30] [ 1]  / answers: 1 / hits: 28446  / 13 Years ago, mon, january 16, 2012, 12:00:00

The only examples I have been able to find of people using $.each are html samples, and it's not what I want. I have the following object:



var obj = {
obj1: 39,
obj2: 6,
obj3: 'text'
obj4: 'text'
obj5: 0
};


I loop through the object like so:



$(array).each(function(index, value) {
// ...
});


I want to sort by obj3 and obj4. Preferrably not using an asynchronous method, how can I sort the results before (or during) output? (I also don't want to loop through this twice, as there could be hundreds at any given time.


More From » jquery

 Answers
2
var array = {
obj1: 39,
obj2: 6,
obj3: 'text'
obj4: 'text'
obj5: 0
};


is not an array (its name notwithstanding). It is an object. The idea of sorting by obj3 and obj4 doesn't really make sense.



Now, if you were to convert this object to an array of objects, you could sort that array with the array.sort method.



var array = [
{ obj1: 39,
obj2: 6,
obj3: 'text'
obj4: 'text'
obj5: 0
},{ obj1: 40,
obj2: 7,
obj3: 'text2'
obj4: 'text3'
obj5: 0
}
];

array.sort(function(a, b) {

var textA = a.obj3.toLowerCase();
var textB = b.obj3.toLowerCase();

if (textA < textB)
return -1;
if (textA > textB)
return 1;
return 0;
});


and of course to sort by a numeric property, it'd simply be:



array.sort(function(a, b) {
return a.obj1 - b.obj1;
});

[#87984] Sunday, January 15, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvinjovannix

Total Points: 416
Total Questions: 94
Total Answers: 117

Location: South Korea
Member since Sun, Aug 8, 2021
3 Years ago
;