2

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.

3 Answers 3

6

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);

Sign up to request clarification or add additional context in comments.

7 Comments

This is the answer you are looking for.
Hi Eddie, thanks for the answer. I just edited my question a little bit. I forgot that I don't always know the length of the innerArrays. The array is dynamically created so sometimes the innerArray length could be 6 values, sometimes 20. But the innerArray's will always be the same length. Will this solution work if this is the case? Is there a way to loop over the length of the innerArray and do this same thing?
You mean, it could be something like ['Company A','A-Email','A-Phone',2,5,10,40,5,6,7,8,,7,7]?
Correct. I never know how many numbers will follow until I receive the array. But the length's of the innerArrays will always be the same
But the first 3 are all constant, name, email, phone?
|
0

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 );

1 Comment

Hi Ben, thanks for the answer. I just edited my question a little bit. I forgot that I don't always know the length of the innerArrays. The array is dynamically created so sometimes the length could be 6 values, sometimes 20 so there could be num4, num5, num6 etc. sometimes.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.