Remove duplicate values from array, show only unique values in JavaScript

March 3rd, 2023

Few options to show only unique values in Javascript: newSet, filter, foreach loop, lodash or underscore (_uniq)

1const cities = ['Rio', 'London', 'London', 'Rome', 'NY']

newSet

1const uniqueCities = Array.from(new Set(cities));
2//or
3const uniqueCities = [...new Set(cities)];

filter

1const uniqueCities = cities.filter((city, index) => cities.indexOf(city) == index)

lodash / underscore: _uniq

1_.uniq([1, 2, 1, 3, 1, 4]); // [1, 2, 3, 4]

foreach

1const unique = []
2 
3cities.forEach(city =>
4 if(!unique.includes(city)){
5 uniqueCities.push(city)
6 }
7)

Php

1$cities = ['Rio', 'London', 'London', 'Rome', 'NY']
2 
3$uniqueCities = array_unique($cities) // ['Rio', 'London', 'Rome', 'NY']

find duplicates, count duplicates

1$duplicateCities = array_diff_key($cities, $uniqueCities) // [London]
2 
3array_count_values($duplicateCities); // 1