-2

My Database Contains duplicate values but I want to display unique data in dropdown in react. I have tried using map but its not working

here is the code:

array.map(item => item.city)
  .filter((value, index, self) => self.indexOf(value) === index)
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • first filter out the unique into a new array then map through it. – cmgchess Nov 10 '21 at 10:22
  • There are tons of examples including here on stack overflow: https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates – user2555515 Nov 10 '21 at 10:24
  • 1
    Does this answer your question? [Remove duplicate values from JS array](https://stackoverflow.com/questions/9229645/remove-duplicate-values-from-js-array) – Ashish Kamble Nov 10 '21 at 10:25
  • You can do as `self.indexOf(value, index + 1) === -1)` inside filter – DecPK Nov 10 '21 at 10:26

2 Answers2

0

you can use JS Set

var array = [{city: 'Colombo'}, {city: 'Colombo'}, {city: 'Kandy'}, {city: 'Kandy'} ];

var uniqCities = [...new Set(array.map(e => e.city))];

console.log(uniqCities)
Azad
  • 5,144
  • 4
  • 28
  • 56
0
var arrayWithDuplicates = [
{"type":"LICENSE", "licenseNum": "12345", state:"NV"},
{"type":"LICENSE", "licenseNum": "A7846", state:"CA"},
{"type":"LICENSE", "licenseNum": "12345", state:"OR"},
{"type":"LICENSE", "licenseNum": "10849", state:"CA"},
{"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
{"type":"LICENSE", "licenseNum": "12345", state:"NM"}];

function removeDuplicates(originalArray, prop) {
 var newArray = [];
 var lookupObject  = {};

 for(var i in originalArray) {
    lookupObject[originalArray[i][prop]] = originalArray[i];
 }

 for(i in lookupObject) {
     newArray.push(lookupObject[i]);
 }
  return newArray;
 }

 var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");
 console.log("uniqueArray is: " + JSON.stringify(uniqueArray));

ref : here

Yui-Yukino
  • 26
  • 1
  • 3