PDA

View Full Version : Javascript object arrays



HighHopes_
12-21-2009, 09:58 AM
Hi i am confused in one topic and need help,

I have a javascript array containing objects like;
Object values are ordered as Type, Amount and count.

Object 1 => ("A" , 100 ,10)
Object 2 => ("C" , 50 ,10)
Object 3 => ("A" , 100 ,20)
Object 4 => ("B" , 200 ,10)
Object 5 => ("A" , 10 ,10)
Object 6 => ("B" , 100 ,10)
Object 7 => ("C" , 100 ,5)
Object 8 => ("C" , 50 ,5)

In the end i want to group these objects like ;

("A" , 100,30) (Note : 30 = 20 +10)
("A" , 10,10)


("B" , 200,10)
("B" , 100,10)


("C" , 100,5)
("C" , 50,15) 15 = 10 + 5


How can i do this in javascript, note that the new types will be added to this array ?

gusblake
12-21-2009, 10:27 AM
Could you explain it a bit more clearly - what's the intended purpose of the code?


(Note : 30 = 20 +10)

Where does that come from?

HighHopes_
12-21-2009, 11:39 AM
There are two "A" with the amount 100. So the count must be 20+10 = 30 ..

Object 1 => ("A" , 100 ,10)
Object 3 => ("A" , 100 ,20)

Purpose is, thinking that type and the amount combination is unique. I want to group the types according to their amounts. So at the end the counts must be the total of the all. "A" type with the amount 100 must have the count 20+10 = 30.

gusblake
12-21-2009, 01:53 PM
Ok. Can 'Object1' etc be properties of a container object? For example:



var container={
original: {Object1: {type:"A", amount:100, count:10}, Object2: {type:"C", amount:50, count:10}},
sorted: {}
}
If so, you could make a method which loops through all the 'original' objects and creates associative arrays inside 'sorted', with one dimension being the type and the other being the amount. Then you could access the unique 'count' values for each type/amount group like so: alert(container.sorted["A"][100]) //alerts 30.



container.sort=function() {
for(i in this.original) { //initialise the arrays in sorted
if(!this.sorted[this.original[i].type]) this.sorted[this.original[i].type]=[]; //EDIT - conditional prevents some values returning NaN if there is more than one element to a group.
this.sorted[this.original[i].type][this.original[i].amount]=0;
}

for(i in this.original) { //loop through the original objects again, adding their 'counts' to the appropriate object in 'sorted'
this.sorted[this.original[i].type][this.original[i].amount]+=this.original[i].count;
}
}

Old Pedant
12-21-2009, 09:32 PM
I'm a bit confused by this part:

note that the new types will be added to this array

So that means that AFTER this process the array will consist of


Object 1 => ("A" , 100 ,10)
Object 2 => ("C" , 50 ,10)
Object 3 => ("A" , 100 ,20)
Object 4 => ("B" , 200 ,10)
Object 5 => ("A" , 10 ,10)
Object 6 => ("B" , 100 ,10)
Object 7 => ("C" , 100 ,5)
Object 8 => ("C" , 50 ,5)
Object 9 => ("A", 100, 30)
Object 10 => ("C", 50, 15)


You want to ADD the objects in red??? You don't want to *ALSO* remove the ones in blue???