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:
- sort the array on
keyA
- 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!
question from:
https://stackoverflow.com/questions/65602272/how-would-i-concat-and-group-similar-values-in-an-array-of-object 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…