简体   繁体   中英

How to combine and group arrays in javascript

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..

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:

在此处输入图片说明

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

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' }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM