Cannot remove duplicates

Viewed 43

I follow this question to achieve the result Remove duplicate values from JS array. Also, I read a lot of stuff like https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set, but unfortunately, values are still duplicated

.map((devicedetails, index) => {
  return (
    <option key={index} value={[...new Set(devicedetails.groupName)]}>
      {[...new Set(devicedetails.groupName)]}
    </option>
  );
});

Note: I thought it's clear but **devicedetails ** consists of JSON with multiple values, not just one

Result: enter image description here

Updated:

before return: var list = [];

 filteredList.map((devicedetails, index) => {
                          list.push(devicedetails.groupName);
                          if (list.length === index + 1) {
                            var data = [...new Set(list)];
                            data.forEach((element) => {
                              return <option value={element}>{element}/option>;
                            });
                          }
                        })

But in this case, is returning nothing in option but it's working I check via console.log(element)

2 Answers

Instead of looping over devicedetails, outside of the return, create a modified array using the spread syntax and set it as a new variable. Then loop over that instead.

e.g.

const array = ['test', 'testing', 'test', 'test1234', 'testing']

const updatedArray = [...new Set(array)]

console.log(updatedArray)

You need to remove duplicates of the whole array and then map over the version with duplicates removed.

[...new Set(myArray)].map((devicedetails, index) => (
  <option key={index} value={devicedetails.groupName}>
    {devicedetails.groupName}
  </option>
));
Related