Itsik Mauyhas Itsik Mauyhas - 3 years ago 224
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
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){


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

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

List data -

"uid": "23",
"time": "2017-10-01 16:00:35.515",
"SUGNIA": "stock",
"uid": "29",
"SECURITYNUM": 629014,
"time": "2017-09-28 16:32:26.432",
"SUGNIA": "holdings",

"uid": "id",
"time": "2017-09-28 16:33:20.25",
"SUGNIA": "stock",
"SECURITYNAME": "google",

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)){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download