I have an array of objects where I want to return only the unique objects based on their object Id.
I've tried to loop in the existing array data
then find if the element was already add to a newly created array arr
which should contain only the unique values, but it didn't work with me and I believe that I am missing something here or there.
Here is the current array :
[
{
"objectId": "WMtwbyhFI6",
"cuisineNameEn": "Cafe",
"ordersNo": 20,
"hidden": false
},
{
"objectId": "QJSNTMpq5F",
"ordersNo": 24,
"cuisineNameEn": "Italian",
"hidden": false
},
{
"objectId": "iLXKswFRGa",
"ordersNo": 5,
"cuisineNameEn": "Japanese",
"hidden": true
},
{
"objectId": "Db0MeihpJE",
"ordersNo": 6,
"cuisineNameEn": "Fast Food",
"hidden": false
},
{
"objectId": "QJSNTMpq5F",
"ordersNo": 24,
"cuisineNameEn": "Italian",
"hidden": false
},
{
"objectId": "Db0MeihpJE",
"ordersNo": 6,
"cuisineNameEn": "Fast Food",
"hidden": false
},
{
"objectId": "Db0MeihpJE",
"ordersNo": 6,
"cuisineNameEn": "Fast Food",
"hidden": false,
},
{
"objectId": "Db0MeihpJE",
"ordersNo": 6,
"cuisineNameEn": "Fast Food",
"hidden": false
},
{
"objectId": "Db0MeihpJE",
"ordersNo": 6,
"cuisineNameEn": "Fast Food",
"hidden": false
},
{
"objectId": "Db0MeihpJE",
"ordersNo": 6,
"cuisineNameEn": "Fast Food",
"hidden": false
},
{
"objectId": "Db0MeihpJE",
"ordersNo": 6,
"cuisineNameEn": "Fast Food",
"hidden": false
}
]
However, this is what I want to return :
[
{
"objectId": "WMtwbyhFI6",
"cuisineNameEn": "Cafe",
"ordersNo": 20,
"hidden": false
},
{
"objectId": "iLXKswFRGa",
"ordersNo": 5,
"cuisineNameEn": "Japanese",
"hidden": true
},
{
"objectId": "Db0MeihpJE",
"ordersNo": 6,
"cuisineNameEn": "Fast Food",
"hidden": false
},
{
"objectId": "QJSNTMpq5F",
"ordersNo": 24,
"cuisineNameEn": "Italian",
"hidden": false
}
]
I've tried the following:
var arr = [];
data.forEach((el)=>{
if (arr.indexOf(el.objectId) === -1) {
arr.push(el)
}
})
However, it didn't work.