1

array name stays and it duplicates and repeating this process just clogs the list up.

Thank you.

        setListItems(contents.data);
        console.log(contents.data);

4
  • Use a Set Commented Jan 19, 2021 at 21:54
  • You are doing it correctly but I believe your contents.data contains duplicate value in itself. Just convert it to Set and back and you should be good to go.. Or you could store set directly in the state instead of array. Whatever you prefer. Commented Jan 19, 2021 at 22:02
  • @rahulpsd18 could you give me an example of how I could convert it to a set and then back again please? Commented Jan 19, 2021 at 22:08
  • Does this answer your question? Get all unique values in a JavaScript array (remove duplicates) Commented Jan 19, 2021 at 22:27

2 Answers 2

1

To convert the array contents.data to Set, do this:

const setData = new Set(contents.data);

That will remove all the duplicate items. Then to convert it back, do this:

const uniqueArray = Array.from(setData);

The above will only work if the original array (contents.data) consisted of primitive values. If it was an array of objects then this will not work as-is and will require some changes.

Sign up to request clarification or add additional context in comments.

4 Comments

I've added both things at the top, hasn't worked. But yeah it's an array of objects, see below for the code
Can you share the object schema here?
the contents is a JSON object with attributes type and data. both of them contain primitive types with type being just a String and data being just an array with Strings
If the array is of primitive data (consists of strings) then the first solution should have worked fine. Please check once again. Add some intermediate logs or use a debugger. I don't think I can help anymore than this here.
1

Taken straight from MSDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#remove_duplicate_elements_from_the_array

// Use to remove duplicate elements from the array

const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]

console.log([...new Set(numbers)])

// [2, 3, 4, 5, 6, 7, 32]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.