I am new to associative arrays and I have this code below. I would like to assign the values for prop
and sumprop[prop]
to a new array, prop1
and prop2
. Appreciate some help here.
var name = new Array();
var amount = new Array();
name[0]="Peter";
amount[0]="50";
name[1]="John";
amount[1]="10";
name[2]="John";
amount[2]="20";
name[3]="Peter";
amount[3]="20";
name[4]="Mary";
amount[4]="40";
var sum = {};
var i;
var prop1 = new Array();
var prop2 = new Array();
for (i = 0; i < amount.length; i++) {
var name = name[i];
var oldSum = sum[name];
if (typeof oldSum === 'undefined') {
oldSum = 0;
}
sum[name] = oldSum + amount[i];
}
for (var prop in sum) {
if (sum.hasOwnProperty(prop)) {
console.log(prop + " " sum[prop]);
// assign to a new array
}
}
I rewrote your code to make your intentions more clear (using better variable names and changing the data's structure):
var people = [
{ name: 'Peter', amount: 50 },
{ name: 'John', amount: 10 }
// etc.
];
var sums = {};
var i, person;
for (i = 0; i < people.length; i++) {
person = people[i];
if (typeof sums[person.name] === 'undefined') {
sums[person.name] = 0;
}
sums[person.name] += person.amount;
}
for (var name in sums) {
if (sums.hasOwnProperty(name)) {
console.log(name, sums[name]);
}
}
Your trying to force arrays to act like dictionaries, which is an uphill battle. You also don't need to use the array constructor (ie new Array()
) because you can just create a new array like this var someVar = [];
.
You probably want:
for (var prop in sum) {
if (sum.hasOwnProperty(prop)) {
prop1.push(prop);
prop2.push(sum[prop]);
}
}
You want this:
for (var prop in sum) {
console.log(prop + " " sum[prop]);
prop1.push(prop);
prop2.push(sum[prop])
}
Also, don't use new Array()
when initializing arrays, use:
var prop1 = [];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.