Magentix
if (OP.statement == false) postCount++;
- Reaction score
- 107
Hey guys, I've encountered a rather annoying problem with IE7 (and 6/8?)
I'm trying to sort an array of objects, but after swapping their places in the array, I want to let the objects have some parameters of their "old place".
In the example below, I want to have 3 names called out: A, B and C. Now I want A, B and C to have ascending ages, without calling them in a different order.
Solution: I grab my magic stick and give A the youngest age, B the middle age and C the oldest one.
The code below works fine in FF/Chrome, but IE won't let me manipulate objects that are passed to the .sort() method.
To get you started, the process of the first loop goes as follows:
A-3,B-1,C-2
-> detect lower age, swap names ->
B-3,A-1,C-2
-> because the func returns +2, javascript .sort() swaps the objects ->
A-1,B-3,C-2
-> because a swap occured (even though only age swapped), .sort() continues normally
(To test the case below you'll need jQuery)
I'm trying to sort an array of objects, but after swapping their places in the array, I want to let the objects have some parameters of their "old place".
In the example below, I want to have 3 names called out: A, B and C. Now I want A, B and C to have ascending ages, without calling them in a different order.
Solution: I grab my magic stick and give A the youngest age, B the middle age and C the oldest one.
The code below works fine in FF/Chrome, but IE won't let me manipulate objects that are passed to the .sort() method.
To get you started, the process of the first loop goes as follows:
A-3,B-1,C-2
-> detect lower age, swap names ->
B-3,A-1,C-2
-> because the func returns +2, javascript .sort() swaps the objects ->
A-1,B-3,C-2
-> because a swap occured (even though only age swapped), .sort() continues normally
(To test the case below you'll need jQuery)
Code:
function test() {
var obj = [{'name':'A','age':3},{'name':'B','age':1},{'name':'C','age':2}];
$.each(obj,function(){
alert(this.name+', aged: '+this.age);
});
obj.sort(function(a,b){
if (a.age > b.age) {
var tempobj = b.name;
b.name = a.name;
a.name = tempobj;
}
return a.age - b.age;
});
$.each(obj,function(){
alert(this.name+', aged: '+this.age);
});
}