Consider this array of objects:
[
{
key1: "AAA",
key2: "BBB"
},
{
key1: "BBB",
key2: "CCC"
},
{
key1: "CCC",
key2: "DDD"
},
{
key1: "XXX",
key2: "YYY"
},
]
How does one write a concise function to group them, so that if the key1 of the next object is equal to the key2 of the previous, the subsequent objects will become one?
The desired output of the above example:
[
{
key1: "AAA",
key2: "DDD"
},
{
key1: "XXX",
key2: "YYY"
},
]
CodePudding user response:
You can do this with reduce:
const input = [
{
key1: "AAA",
key2: "BBB"
},
{
key1: "BBB",
key2: "CCC"
},
{
key1: "CCC",
key2: "DDD"
},
{
key1: "XXX",
key2: "YYY"
},
]
const result = input.reduce( (acc,i) => {
const last = acc[acc.length-1];
if(last === undefined || last.key2 != i.key1){
acc.push({...i});
}
else{
acc[acc.length-1] = {...last, key2:i.key2};
}
return acc;
},[]);
console.log(result);
