i have a script where i am trying to get the unique object based on state from the array of objects
The below scripts works fine, but I have one case where I have nested object in one kind of state has a sub-state, so I want to find the unique from the array of objects and get the unique.
The below snippet I am able to get the first level, but if we see the state => “EF” has a sub_state_details, so I need to get the unique from sub_state_details if state is EF
let inputArray = [{
state: "AB",
}, {
state: "BC",
}, {
state: "BC",
}, {
state: "CD",
}, {
state: "CD",
}, {
state: "DE",
}, {
state: "EF",
sub_state_details: {
state: "EF-1"
}
}, {
state: "EF",
sub_state_details: {
state: "EF-1"
}
},
{
state: "EF",
sub_state_details: {
state: "EF-2"
}
}
]
let resArr = []
inputArray.filter(function(item) {
var i = resArr.findIndex(x => (x.state == item.state));
if (i <= -1) {
resArr.push({
state: item.state
});
}
return null;
});
console.log(resArr)
expected output
let output = [{
state: "AB",
}, {
state: "BC",
}, {
state: "CD",
}, {
state: "DE",
}, {
state: "EF-1",
},{
state: "EF-2",
}]