I am currently working on implementing the filter method on an array that contains objects like the following:
{
"start": 1234,
"end": 4321,
"count": 0
}
My goal is to remove duplicates from the array while incrementing the count property.
So far, I have successfully filtered the array based on the start property with this code snippet:
var temp = {};
myArray = myArray.filter(function(obj) {
if (obj.start in temp) {
return false;
} else {
temp[obj.start] = true;
return true;
}
});
Now, I want to create a filter that follows these conditions (temporary object referred to as tempObj and current object as obj for clarity):
- If obj.start === tempObj.start && obj.end === tempObj.end, obj.count += 1
- If obj.start === tempObj.start || obj.end === tempObj.end, obj.count = tempObj.count + 1
- If obj.start > tempObj.start && obj.end < tempObj.end, obj.count = tempObj.count + 1
- Otherwise, add a new element to temp with count = 1
Is it achievable using the filter method? If not, what would be the correct approach? I prefer to avoid using any framework.
EDIT: Following RobG's request for clarification, here is an example of input and output:
Example input:
myArray = [{
"start": 1105,
"end": 1501,
"count": 0
},
{
"start": 1105,
"end": 1003,
"count": 0
},
{
"start": 1110,
"end": 1120,
"count": 0
},
{
"start": 1105,
"end": 1003,
"count": 0
},
{
"start": 1115,
"end": 1120,
"count": 0
}]
Desired output:
myArray = [{
"start": 1105,
"end": 1501,
"count": 1
},
{
"start": 1105,
"end": 1003,
"count": 3
},
{
"start": 1110,
"end": 1120,
"count": 1
}
{
"start": 1115,
"end": 1120,
"count": 1
}]