How do I create an array of unique field values in React with data from Firestore?

Viewed 333

I'm retrieving the data from Firestore and then displaying it in a list with the following code:

{ docs && docs.map(doc => (
     <ul key={doc.id}>               
        <li>
             <button>
                  <Link to={`/tag/${doc.myTag}`}>
                      {doc.myTag}
                  </Link>
             </button>
        </li>
     </ul>
))}

This outputs every tag. At first I want array of data fetched from Firestore and set into my own new array. After that, I would like to remove duplicates and show just unique tags. What would be the correct way to do this?

I'm thinking to create a new array and then use filter + indexOf, or something similar, but I need to create an array of all the tags first, which is where I'm having the problem.

Any help very much appreciated.

3 Answers

const docs = [ {tag: 'test'},
              {tag: 'test1'},
              {tag: 'test2'},
              {tag: 'test2'},
              {tag: 'test2'}
             ];

const unique = [...new Set(docs.map(({tag})=> tag))];
console.log(unique);

If I correctly get your question, the following should help:

To get data from Firestore to array. First of all you have to iterate over an object of Firestore and then save them to a new array.

For Example:

 documentName.firestore().collection("collectionName").doc(yourDoc).get().then(queryResult =>{

      //Here create new array and push your data to array after making it unique 
      //using set or any other function

  });

queryResult is a DocumentSnapshot: It "contains data read from a document in your Firestore database. The data can be extracted with .data() or .get() to get a specific field."

Maybe solution is is new Set?

let clearDocs = [...new Set(docs)];
Related