Get sum of columns if values of other columns match

送分小仙女□ 提交于 2021-01-28 14:12:11

问题


I have this matrix algorithm problem:

Input:

const testObj = [
 ['Anna', 10, 'Monday'],
 ['Anna', 15, 'Wednesday'],
 ['Beatrice', 8, 'Monday'],
 ['Beatrice', 11, 'Wednesday'],
 ['Anna', 4, 'Wednesday'],
 ['Beatrice', 5, 'Monday'],
 ['Beatrice', 16, 'Monday']
]

Output:

let resultObj = [
 ['Anna', 10, 'Monday'],
 ['Beatrice', 11, 'Wednesday'],
 ['Anna', 19, 'Wednesday'],
 ['Beatrice', 27, 'Monday']
]

Basically, if it's the same person (col0) and the same day (col2), get the sum of col1, and merge.

I'm solving this with javascript but any suggestion in any language will do. I've done this:

const solveThis = async(obj) => {
 for (let i = 0; i < obj.length; i += 1) {
  if (obj[i + 1] && (obj[i][0] === obj[j][0]) && (obj[i][2] === obj[j][2])) {
   let sum = obj[i][1] + obj[j][1],
       newRow = new Array(obj[i + 1][0], sum, obj[i + 1][2])
   obj.push(newRow)
   let indexi = obj.indexOf(obj[i]),
       indexj = obj.indexOf(obj[j])
   obj.splice(indexi, 1)
   obj.splice(indexj, 1
  }
 }
  return obj
}

solveThis(testObj).then(result => console.log(result))

and it doesn't work.


回答1:


First make a object with name|day keys and then get values.

const data = [['Anna', 10, 'Monday'],['Anna', 15, 'Wednesday'],['Beatrice', 8, 'Monday'],['Beatrice', 11, 'Wednesday'],['Anna', 4, 'Wednesday'],['Beatrice', 5, 'Monday'],['Beatrice', 16, 'Monday']]

const result = data.reduce((r, [name, v, day]) => {
  const key = `${name}|${day}`;
  if(!r[key]) r[key] = [name, v, day];
  else r[key][1] += v;
  return r;
}, {})

console.log(Object.values(result))



回答2:


You can use the array .reduce method to create the new array. For each item, use .find to see if there is an existing item with matching name and day. If so, add the values, otherwise put the item into the new array.

Example:

const testObj = [
 ['Anna', 10, 'Monday'],
 ['Anna', 15, 'Wednesday'],
 ['Beatrice', 8, 'Monday'],
 ['Beatrice', 11, 'Wednesday'],
 ['Anna', 4, 'Wednesday'],
 ['Beatrice', 5, 'Monday'],
 ['Beatrice', 16, 'Monday']
];

function merge(arr) {
  return arr.reduce((merged, item) => {
    const existing = merged.find(o => o[0] === item[0] && o[2] === item[2]);
    existing
      ? existing[1] += item[1]
      : merged.push(item);
      
    return merged;
  }, []);
}

console.log(merge(testObj));


来源:https://stackoverflow.com/questions/50419051/get-sum-of-columns-if-values-of-other-columns-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!