I have below array with objects which includes duplicates type values. I need unique array of objects based on immediate same type values.
Note:
If any object has immediate next same type values then it will make one unique array list. Else it will include another unique object list with same type value.
Array :
[
{ "object": 1, "start": "2018-07-08", "end": "2018-12-31", "type": "A", "user": "ABCD" },
{ "object": 2, "start": "2018-12-31", "end": "2019-06-26", "type": "A", "user": "ABCD" },
{ "object": 3, "start": "2019-06-26", "end": "2019-12-31", "type": "B", "user": "PQRS" },
{ "object": 4, "start": "2019-12-31", "end": "2020-06-31", "type": "B", "user": "PQRS" },
{ "object": 5, "start": "2021-12-31", "end": "2022-12-31", "type": "A", "user": "ABCD" },
{ "object": 6, "start": "2012-12-31", "end": "2022-06-26", "type": "A", "user": "ABCD" },
{ "object": 7, "start": "2022-06-26", "end": "2022-12-31", "type": "A", "user": "ABCD" },
{ "object": 8, "start": "2022-12-31", "end": "2023-06-26", "type": "A", "user": "ABCD" }
]
In above array object 2 is immediate after object 1 with same type A value therefore it make one unique list with A. And after that objects 3,4,5 has immediate basis on type B value therefore it created another unique list. After object 2, object 3 there is no similar "type" value so first unique list end there. But again object 5,6,7,8 has immediate basis type A value therefore it created another unique list.
I expected below Output (if any object has one after another same value then it will create unique list else it will end there and make another separate objects list) :
[
{
"A":[
{
"object":1,
"start":"2018-07-08",
"end":"2018-12-31",
"type":"A",
"user":"ABCD"
},
{
"object":2,
"start":"2018-12-31",
"end":"2019-06-26",
"type":"A",
"user":"ABCD"
}
]
},
{
"B":[
{
"object":3,
"start":"2019-06-26",
"end":"2019-12-31",
"type":"B",
"user":"PQRS"
},
{
"object":4,
"start":"2019-12-31",
"end":"2020-06-31",
"type":"B",
"user":"PQRS"
}
]
},
{
"A":[
{
"object":5,
"start":"2021-12-31",
"end":"2022-12-31",
"type":"A",
"user":"ABCD"
},
{
"object":6,
"start":"2012-12-31",
"end":"2022-06-26",
"type":"A",
"user":"ABCD"
},
{
"object":7,
"start":"2022-06-26",
"end":"2022-12-31",
"type":"A",
"user":"ABCD"
},
{
"object":8,
"start":"2022-12-31",
"end":"2023-06-26",
"type":"A",
"user":"ABCD"
}
]
}
]
3
Answers
What you want is something like
lodash
suniqBy
, see documentation here https://lodash.com/docs/4.17.15#uniqByTry if it works for you.
You could take a closure over
type
anf check the type from each element. If same, add to the last element of the result set, if not, create a new object. Updatetype
.