Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 removing duplicates from an JSON array

I have a problem with filter in my JSON array when I move my app to Angular2 . In Angular 1.x that was easier. I used 'unique' in filter and this remove all duplicates.

apps:

{"app":"database_1",
 "host":"my_host1",
 "ip":"00.000.00.000"
},
{"app":"database_1",
 "host":"my_host1",
 "ip":"00.000.00.000"
},
{"app":"database_2",
 "host":"my_host2",
 "ip":"00.000.00.000"
},
{"app":"database_2",
 "host":"my_host2",
 "ip":"00.000.00.000"
}

Part of html code:

    <div *ngFor='#appsUnique of apps '>
        <div class="row dashboard-row">
            <div class="col-md-2">
               <h4>{{appsUnique.app }}</h4>
            </div>
        </div>
    </div>

And result is:

database_1
database_1
database_2
database_2

I want to get result:

database_1
database_2

How can I remove duplicates from an array?

like image 396
notsaltydev Avatar asked Jul 21 '16 10:07

notsaltydev


People also ask

How can I remove the duplicate items in an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays.sort(arr) method.

How do you remove duplicate objects from array of objects in TypeScript?

Array. filter() removes all duplicate objects by checking if the previously mapped id-array includes the current id ( {id} destructs the object into only its id).

How do I remove duplicates in ab initio?

you can achieve below requirement using sort and dedup sort . first sort the input data with key as distance and dedup the sorted data with same key as distance and keep (first) you will get desire output.

How do I remove duplicates from a set in Python?

If the order of the elements is not critical, we can remove duplicates using the Set method and the Numpy unique() function. We can use Pandas functions, OrderedDict, reduce() function, Set + sort() method, and iterative approaches to keep the order of elements.


2 Answers

Mybe it can help you

myList = ["One","two","One","tree"];

myNewList =  Array.from(new Set(myList ));
like image 163
ABDERRAHIME FARHANE Avatar answered Oct 26 '22 03:10

ABDERRAHIME FARHANE


I have a solution for this problem :)

Array.from(new Set([{"app":"database_1",
 "host":"my_host1",
 "ip":"00.000.00.000"
},
{"app":"database_1",
 "host":"my_host1",
 "ip":"00.000.00.000"
},
{"app":"database_2",
 "host":"my_host2",
 "ip":"00.000.00.000"
},
{"app":"database_2",
 "host":"my_host2",
 "ip":"00.000.00.000"
}].map((itemInArray) => itemInArray.app)))

More about Array.from & Set

Thanks all for help :)

like image 36
notsaltydev Avatar answered Oct 26 '22 04:10

notsaltydev