This is regarding JavaScript. I have a response data like this which contains pairs of objects (note that the pairs can also be of 3 or 4 or any number and the pair ids are sorted). I want to alter the data such that after each matching pairs, I append one object.
[
{
pairId: 1,
name: "abc",
count: 10
},
{
pairId: 1,
name: "xyz
count: 20
},
{
pairId: 2,
name: "abc"
count: 15
},
{
pairId: 2,
name: "xyz,
count: 25
}
]
I want to achieve the data where I append one object after each matching pairs updating the count like this
[
{
pairId: 1,
name: "abc",
count: 10
},
{
pairId: 1,
name: "xyz
count: 20
},
{
pairId: 1,
count: 30
},
{
pairId: 2,
name: "abc"
count: 15
},
{
pairId: 2,
name: "xyz,
count: 25
}
{
pairId: 2,
name: "mno,
count: 5
}
{
pairId: 2,
count: 45
}
]
Can anybody help achieve this?
While this question seems like a duplicate but I also wanted to know how to achieve pushing item to the end of last matching paired item.
3
Answers
You could do this with a loop and try to juggle the current "run" of matching ids, and handle when you encounter a new id, and handle the start/end edge cases.
But a simpler solution is to group your elements by id, and for each group, if it has more than one element, add a new element with the sum of that group’s
count
field.something like this: it is iterate through all cycle and if the id have changed then the pair also changed and the algorithm can calculate and paste new element, also in the end of cycle pushed last element.
here is a solution with manual loops and by keeping track of the previous id and the the sums. the current
pairId
not equal toprevPairId
means a new group has started then we push the summed object to the array and reset the group sumprevSum
and set theprevPairId
to currentpairId
.count !== undefined
check to handle edge case happening at the end of the array wheredata[i]
isundefined
. (Note the loop is running for array length + 1 times)