简体   繁体   中英

Reduce an Array of Arrays by value

I have an array of arrays similar to the structure below. I am trying to reduce the array as efficiently as possible based on the Company Name (ex. Company A). So basically, where the company names are the same, combine the inner array so that the numbers in each position get added to the matching array's numbers in the corresponding position. Also if one of the arrays has a missing email or phone, take the email or phone position that has a value. The resultArray at the bottom shows the result I am trying to achieve.

*Note - I don't know the length of numbers following a company. The length is dynamically set, but the length of each inner array will always be the same. So sometimes all the innerArray's are 6 values, other times they could be 20 values in length.

var array = [
    [Company A, A-Email, A-Phone, 2, 5, 10],
    [Company A, A-Email, , 1, 10, 7],
    [Company A, , A-Phone, 3, 2, 4],
    [Company B, B-Email, , 1, 10, 7],
    [Company B, B-Email, B-Phone, 5, 10, 8],
    [Company C, C-Email, C-Phone, 3, 2, 1]
  ]
var resultArray = [
    [Company A, A-Email, A-Phone, 6, 17, 21],
    [Company B, B-Email, B-Phone, 6, 20, 15],
    [Company C, C-Email, C-Phone, 3, 2, 1]
  ]

So originally I was trying something like this because the array had already been sorted by company name:

for (var i = 0; i < array.length - 1; i++) {
  var firstArray = array[i]
  var nextArray = array[i + 1]
  if (nextArray[0] == firstArray[0]) {
    for (var t = 3; t <= firstArray.length; t++) {
      firstArray[t] = firstArray[t] + nextArray[t]

    }
    resultArray.push(firstArray);
} else {continue;}

I have a large set of data and doing it this way was really operation heavy and my function timed out so I'm not completely sure if it even worked. I started to try to do a reduce method with a hash table but I couldn't quite figure it out. Any idea's on how to do this most efficiently?

Also I can't use jQuery, so purely vanilla javascript please.

You can use ES6 reduce to summarize the array into an object. And use Object.values to convert the object into an array.

Note: Fiddle does not (currently) working. So you might need to test it on your browser.

 var array=[['Company A','A-Email','A-Phone',2,5,10],['Company A','A-Email',,1,10,7],['Company A',,'A-Phone',3,2,4],['Company B','B-Email',,1,10,7],['Company B','B-Email','B-Phone',5,10,8],['Company C','C-Email','C-Phone',3,2,1]]; var resultArray = Object.values(array.reduce((c, v) => { c[v[0]] = c[v[0]] || [v[0], null, null].concat(new Array(v.length - 3).fill(0)); c[v[0]][1] = c[v[0]][1] || v[1]; //Update Email c[v[0]][2] = c[v[0]][2] || v[2]; //Update Phone //Loop thru the numbers and add for (var i = 3; i < v.length; i++) c[v[0]][i] += ( v[i] || 0 ); return c; }, {})); console.log(resultArray); 

Hash tables would be the correct approach (assuming 'Company A' etc are strings; otherwise it's a Map).

var companies = {};
for ( var i = 0; i < array.length; i++ ) {
    var item = array[ i ];
    var name = item[ 0 ];
    var phone = item[ 1 ];
    var num1 = item[ 2 ];
    var num2 = item[ 3 ];
    var num3 = item[ 4 ];
    if ( companies[ name ] ) {
        var record = companies[ name ];
        record[ 1 ] = record[ 1 ] || email;
        record[ 2 ] = record[ 2 ] || phone;
        record[ 2 ] += num1;
        record[ 3 ] += num2;
        record[ 4 ] += num3;
    } else {
        companies[ name ] = [ name, email, phone, num1, num2, num3 ]
    }
}
var resultArray = Object.values( companies );

You can try something like below. The main point is to use reduce() to get an object full of correct data then flatten it back into arrays using Object.values() .

 //initial data var data = [ ['Company A', 'A - Email', 'A - Phone', 2, 5, 10], ['Company A', 'A - Email', , 1, 10, 7], ['Company A', , 'A - Phone', 3, 2, 4], ['Company B', 'B - Email', , 1, 10, 7], ['Company B', 'B - Email', 'B - Phone', 5, 10, 8], ['Company C', 'C - Email', 'C - Phone', 3, 2, 1] ]; //reduce function to organize data var reducer = function(accumulator, currentValue, currentIdx) { var [companyId, email, phone, i, j, k] = currentValue; accumulator[companyId] = { email: !accumulator[companyId] ? email : !accumulator[companyId].email ? email : accumulator[companyId].email, phone: !accumulator[companyId] ? phone : !accumulator[companyId].phone ? phone : accumulator[companyId].phone, i: (accumulator[companyId] ? accumulator[companyId].i : 0) + i, j: (accumulator[companyId] ? accumulator[companyId].j : 0) + j, k: (accumulator[companyId] ? accumulator[companyId].k : 0) + k } return accumulator; } var rawData = data.reduce(reducer, {}); //organize data back into array of arrays var formattedData = []; for (key in rawData) { formattedData.push([key].concat(Object.values(rawData[key]))); } console.log(formattedData); 

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