Reputation: 31
Hi I see there are loads of examples but none explains what I need done.
I want to create and add items to a 2 Dimensional array and sort dynamically.
Some code I have been messing around with:
var Amount = new Array(new Array()); //MULTI ARRAY
var a = 0; //COUNTER
$("input[id^='AmountSpent']").each(function(){
Amount[a][a] = [a, $(this).val()]; //THIS IS WHERE I GET STUCK... HOW TO ASSIGN VALUES
a = a + 1;
});
After that I want to sort the array.
So if the array looks like this:
Amount = [[1,2,3,4],[$200,$300,$100,$600]]
I want to sort highest amount first: $600, $300, $200, $100
Can anyone please help me.
U P D A T E
Using the code i got from Rory(Thanks a lot) I am doing the following:
var amounts = [];
$("input[id^='AmountSpent']").each(function(i, el){
amounts.push({ index: i + 1, value: $(el).val() });
});
amounts.sort(function(a, b) {
if(a.value < b.value) return 1;
if(a.value > b.value) return -1;
return 0;
});
To loop through the array I am doing :
for (ii = 0; ii < amounts.length; ++ii) {
console.log(amounts[ii].index + " - " + amounts[ii]); //
}
The Result I get is :
1 - [object object]
2 - [object object]
3 - [object object]
Upvotes: 1
Views: 7520
Reputation: 337560
A multidimensional array is probably overkill for this. Personally I'd use an array of objects - assuming you need to store the index at all.
var amounts = [];
$(".foo").each(function(i, el){
amounts.push({ index: i + 1, value: $(el).val() });
});
amounts.sort(function(a, b) {
if(a.value < b.value) return 1;
if(a.value > b.value) return -1;
return 0;
});
Update
Your loop code doesn't access the value
property, try this:
for (ii = 0; ii < amounts.length; ++ii) {
console.log(amounts[ii].index + " - " + amounts[ii].value);
}
Upvotes: 3