Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - Group by 2 columns based on parameters and sum up total


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My code below works with any number of keys. Define your wanted keys.

Not sure whether you wanted to concatenate all other fields though.

const data = [{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5", Status: "Done", Month: "May" },
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10", Status: "Started", Month: "May" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15", Status: "Done", Month: "June" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20", Status: "Started", Month: "Aug" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25", Status: "Done", Month: "Apr" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30", Status: "NotStarted", Month: "May" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35", Status: "Done", Month: "Oct" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40", Status: "NotStarted", Month: "Dec" }];

const keys = ["Phase", "Step"];
function matches(table, entry, keys) { // finds item with same values
  return table.find(e => keys.every(k => e[k] == entry[k]));
}
const result = data.reduce((cur, val) => {
  let alreadyIn = matches(cur, val, keys);
  if (alreadyIn) {
    alreadyIn['Value'] = (parseInt(alreadyIn['Value']) + parseInt(val['Value'])).toString();
  } else {
    cur.push(val);
  }
  return cur;
}, []);

console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...