sampleData = [{
RouteId: "1",
InDirection: "1",
AreaCode: ["41108", "41109", "41110", "41111"],
}, {
RouteId: "1",
InDirection: "2",
AreaCode: ["41108", "41109", "411011"],
}, {
RouteId: "2",
InDirection: "1",
AreaCode: ["41112", "41114"],
}, {
RouteId: "2",
InDirection: "2",
AreaCode: ["41112", "41114"],
}, {
RouteId: "3",
InDirection: "1",
AreaCode: ["41112", "41114"],
}, {
RouteId: "3",
InDirection: "2",
AreaCode: ["41112", "41114","41108", "41109", "41110"],
}, {
RouteId: "4",
InDirection: "1",
AreaCode: ["41112", "41114","41108", "41110" , "41120", "41121"],
}, {
RouteId: "4",
InDirection: "2",
AreaCode: ["41112", "41114"],
}]
I want to sort above sampleData
based on number of entries in AreaCodes
and get top 20
results. But I only want one object every RouteId
. Every RouteId
can have two types of InDirection = 1 or 2
. So in the above result would like to removed
{
RouteId: "1",
InDirection: "2",
AreaCode: ["41108", "41109", "411011"],
}
since it less entires on AreaCode
as compared to InDirection= 1
so the final sorted result should be
finalResult = [{
RouteId: "1",
InDirection: "1",
AreaCode: ["41108", "41109", "41110", "41111"],
}, {
RouteId: "2",
InDirection: "1",
AreaCode: ["41112", "41114"],
}, {
RouteId: "3",
InDirection: "2",
AreaCode: ["41112", "41114","41108", "41109", "41110"],
}, {
RouteId: "4",
InDirection: "1",
AreaCode: ["41112", "41114","41108", "41110" , "41120", "41121"],
}]
Here I got so far:
const filteredItems = sampleData.filter(item => {
const otherItem = transformedData.find(i => i.RouteId === item.RouteId && i.InDirection !== item.InDirection);
if (otherItem) {
return item.AreaCode.length > otherItem.AreaCode.length;
} else {
return true;
}
});
But this missed condition where length of AreaCode
is equal and the final result is not sorted.