Home > other >  Google Apps Script: How to merge two arrays conditionally?
Google Apps Script: How to merge two arrays conditionally?

Time:01-05

I have a 2D array having a title in its first element of its 1D array and "trailing" or not at the beginning of the title. I like to add trailing data to the end of its same category parent data, "InterestExpense" or "IncomeTax". How can I do that?

array = [['trailingInterestExpense', 4], ['InterestExpense', 1, 2, 3],
  ['trailingIncomeTax', 4], ['IncomeTax', 10, 20, 30]]

My expected result is:

array = [['InterestExpense', 1, 2, 3, 4],['IncomeTax', 10, 20, 30, 40]]

CodePudding user response:

From your expected value of array = [['InterestExpense', 1, 2, 3, 4],['IncomeTax', 10, 20, 30, 40]], I guessed your ['trailingIncomeTax', 4] might be ['trailingIncomeTax', 40]. If my understanding is correct, how about the following sample script?

Sample script:

const keys = ["InterestExpense", "IncomeTax"]; // This is from your question.
const array = [['trailingInterestExpense', 4], ['InterestExpense', 1, 2, 3], ['trailingIncomeTax', 40], ['IncomeTax', 10, 20, 30]]; // This is from your question.

const obj = array.reduce((o, [a, ...b]) => {
  const key = keys.find(k => a.includes(k));
  if (key) o[key] = o[key] ? [...o[key], ...b] : b;
  return o;
}, {});
const res = keys.map(k => [k, ...obj[k].sort((a, b) => a - b)]);
console.log(res) // [["InterestExpense",1,2,3,4],["IncomeTax",10,20,30,40]]

References:

  • Related