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);

  • Use a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) – Randy Casburn Jan 19 '21 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. – rahulpsd18 Jan 19 '21 at 22:02
  • @rahulpsd18 could you give me an example of how I could convert it to a set and then back again please? –  Jan 19 '21 at 22:08
  • Does this answer your question? [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) – mbojko Jan 19 '21 at 22:27

2 Answers2

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]
Da Mahdi03
  • 1,468
  • 1
  • 9
  • 18
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.

rahulpsd18
  • 641
  • 4
  • 12
  • I've added both things at the top, hasn't worked. But yeah it's an array of objects, see below for the code –  Jan 19 '21 at 22:27
  • Can you share the object schema here? – rahulpsd18 Jan 19 '21 at 22:28
  • 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 –  Jan 19 '21 at 23:05
  • 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. – rahulpsd18 Jan 19 '21 at 23:20