Itsik Mauyhas Itsik Mauyhas - 1 year ago 132
Javascript Question

Create unique array based on property

I want to create an array that does not have repeated object(all objects are unique) based on object property and if it is unique I want to push it to this array.
Before sending it to my function I use:

vm.initResponse = angular.fromJson(response);


That push
$$hashKey
to each object.

function initDropDown(list){
console.log('initDropDown', list);
for (var key in list) {
//remove angularjs $$hashKey
var obj = JSON.parse(angular.toJson(list[key]));
//the object I want to push into new array
var filter = {};
filter.prop = obj.SUGNIA;
//if indexOf returns -1 the array does not have this object
if(vm.stockOptionsSelect.indexOf(filter) < 0){
vm.stockOptionsSelect.push(filter);
}

}
}


the list array has many objects with different
SUGNIA
and I want to create an array with all unique ones.

I have removed
$$hashKey
has explained remove-hashKey and using
indexOf
- indexOf.

List data -

[
{
"uid": "23",
"time": "2017-10-01 16:00:35.515",
"SUGNIA": "stock",
"SECURITYNAME": "IBM",
"INDEX_IN_UI": 5
},
{
"uid": "29",
"SECURITYNUM": 629014,
"time": "2017-09-28 16:32:26.432",
"SUGNIA": "holdings",
"SECURITYNAME": "FaceBook",

"INDEX_IN_UI": 10
},
{
"uid": "id",
"time": "2017-09-28 16:33:20.25",
"SUGNIA": "stock",
"SECURITYNAME": "google",
"INDEX_IN_UI": 0
}
]


And my result should be :

[{"prop":"stock"}, {"prop":"holding"}]


But I get duplicates.

Answer Source

The indexOf function does the comparison using strict equality === and since the object you're passing to this function is an object that was just created, it will always return -1.

To fix that, you can use the ...some(...) function instead.

Here is an example:

if(!vm.stockOptionsSelect.some(e => e.prop == obj.SUGNIA)){
    vm.stockOptionsSelect.push({prop:obj.SUGNIA});
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download