Reputation: 121
So I'm getting values and I want to put them into an array:
var values = {25,23,21}
var unit = {PCS,KG,PCS}
I want it to be like this when I put them in an array
array = {25:PCS,23:KG,21:PCS}
and group and add them depending on the unit so the final result will be something like this
totalval = {46:PCS,23:KG}
I can only put those values into separate arrays but I don't know how can I combine and group them..
Upvotes: 0
Views: 79
Reputation: 798
you will have to create objects first and then put them into an array
var obj1 = {
value: 25,
unit: "PCS"
};
...
var array = [ obj1, obj2, obj3, ... ];
then aggregate them accordingly
Upvotes: 1
Reputation: 10556
var values = [25, 23, 21],
unit = ['PCS', 'KG', 'PCS'],
result = {},
tmpval = {},
totalval = {};
for (var i = 0; i < values.length; i++) {
result[values[i]] = unit[i];
tmpval[unit[i]] || (tmpval[unit[i]] = 0);
tmpval[unit[i]] += values[i];
}
for (var i in tmpval) {
totalval[tmpval[i]] = i;
}
// result: { '21': 'PCS', '23': 'KG', '25': 'PCS' }
// totalval: { '23': 'KG', '46': 'PCS' }
Upvotes: 1
Reputation: 2836
https://jsfiddle.net/wyh5a2h2/
I went through reorganizing your code so it makes a bit of sense and came up with this: Hopefully it suits what you are attempting to do:
var items = [
{value: 25, unit: 'PCS'},
{value: 23, unit: 'KG'},
{value: 21, unit: 'PCS'},
]
var numPCS = 0, numKG = 0;
var result = [];
items.forEach(function(elem, index) {
if(elem.unit==='PCS') {
numPCS+=elem.value;
}
if(elem.unit==='KG') {
numKG+=elem.value;
}
});
result.push({value: numPCS, unit: 'PCS'});
result.push({value: numKG, unit: 'KG'});
console.log(result);
Here is the result:
Upvotes: 2