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
222 views
in Technique[技术] by (71.8m points)

javascript - How would I concat and group similar values in an array of object

I have an array of object

const array = [
   {keyA: "HG 386893", count: 1, type: "dha"},
   {keyA: "AL 386893", count: 1, type: "gop"},
   {keyA: "HG 386893", count: 2, type: "ind"},
   {keyA: "NC 386893", count: 1, type: "dha"},
   {keyA: "HG 386893", count: 1, type: "gop"},
   {keyA: "RO 386893", count: 1, type: "ind"}
];

I want to merge keys based on similar keyA property and concat type and add count. So final result will be:

const result = [
   {keyA: "HG 386893", count: 4, type: "dha,ind,gop"},
   {keyA: "AL 386893", count: 1, type: "gop"},
   {keyA: "NC 386893", count: 1, type: "dha"},
   {keyA: "RO 386893", count: 1, type: "ind"}
];

The way I am implementing this is:

  1. sort the array on keyA
  2. loop through sorted array & if previous value = current value, add count and concat type

I know this is not an optimal solution, so I need some help to optimize this in better way. Thanks!


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

1 Reply

0 votes
by (71.8m points)

You can use .reduce:

const array = [
  { keyA: "HG 386893", count: 1, type: "dha" },
  { keyA: "AL 386893", count: 1, type: "gop" },
  { keyA: "HG 386893", count: 2, type: "ind" },
  { keyA: "NC 386893", count: 1, type: "dha" },
  { keyA: "HG 386893", count: 1, type: "gop" },
  { keyA: "RO 386893", count: 1, type: "ind" }
];

const grouped = Object.values(array.reduce((acc,item) => {
  const { keyA, count, type } = item;
  const prev = acc[keyA];
  acc[keyA] = prev 
    ? { ...item, count: prev.count+count, type: `${prev.type},${type}` } 
    : item;
  return acc;
}, {}));

console.log(grouped);

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

...