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]
-
1If there a specific reason that you need it to be a 2 dimensional array? Why not an array of objects which contains both sets of information?adamb– adamb2012年11月16日 15:26:49 +00:00Commented Nov 16, 2012 at 15:26
-
What I need to do is I have a value say a = 900ドル In the array I want to have the sum of the highest values that make up 900ドル so basically I want to get the indexes/id's [4,3] to use for another calculation.Nev– Nev2012年11月16日 15:46:33 +00:00Commented Nov 16, 2012 at 15:46
1 Answer 1
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);
}
3 Comments
Explore related questions
See similar questions with these tags.