0

So I was stuck on a bug in my React App (I am new to react and JS in general) where I wanted to filter a list of company names so that they are all unique and dont repeat. So having access to github copilot I turned it on and out came a solution that worked but I have no idea why or what its doing. If anyone could help me?

    useEffect(() => {
        const companyNames = data.map(app => app.companyName);
        const uniqueCompanies = [...new Set(companyNames)];
        setCompanies(uniqueCompanies);
    },[data]);

I dont understand how [...new Set(companyNames)] filters out the unique names or what is happening. To my understanding you can only use the spread operator on an array that already exists so didn't know where the new was coming from either.

Rhyez
  • 49
  • 4
  • IN SET all values are unique – miyav miyav Apr 16 '22 at 14:23
  • Because that's how `Set` works. It stores the unique values of any type. To understand you should study https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set – BadPiggie Apr 16 '22 at 14:24
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set if you push an already existing value to set it wont be saved – miyav miyav Apr 16 '22 at 14:24
  • `[...Set(...)]` converts the array to a set, discarding duplicates, then back to an array again. The spread operator can be used on various collections, not just arrays. – Stuart Apr 16 '22 at 14:25
  • "To my understanding you can only use the spread operator on an array" - no, you can use it on any [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) object. And Sets implement that interface, so that's why you can use it here. – Robin Zigmond Apr 16 '22 at 14:35

1 Answers1

1

The expression const uniqueCompanies = [...new Set(companyNames)]; contains the following interesting properties:

LauriM
  • 29
  • 3