0

I am querying multiple documents that have the same field value. I do not want to output the same field twice.

db.collection("books")
  .where("ItemType", "==", "Book")
  .orderBy("Author")
  .limit(100)
  .get()
  .then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      let data = doc.data();
      let row = `<tr>
                    <td>${data.Author}</td> 
                 </tr>`;
      let table = document.getElementById("myTable");
      table.innerHTML += row;
    });
  })
  .catch((err) => {
    console.log(`Error: ${err}`);
  });


Output: enter image description here

As you can see the output, the fields are repeating. I don't want that to happen. How do I write my code in such a way that the field value only appears once, and if there is a repeated field value it should not display.

MUHAMMAD ILYAS
  • 1,402
  • 7
  • 23
randomUser786
  • 1,527
  • 3
  • 13
  • 25

2 Answers2

1

As far as I know, firebase doesn't have a "distinct" method. (It would make your request much easier).

So you'll have to create an array and push the values in the loop to it. And before adding its row, you should check if the current value already exists in the array, if not - add it, otherwise - skip.

let authors = [];
db.collection("books")
  .where("ItemType", "==", "Book")
  .orderBy("Author")
  .limit(100)
  .get()
  .then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      let data = doc.data();
      if (!authors.includes(data.Author)) {
        authors.push(data.Author);
        let row = `<tr><td>${data.Author}</td> </tr>`;
        let table = document.getElementById("myTable");
        table.innerHTML += row;
      }
    });
  })
  .catch((err) => {
    console.log(`Error: ${err}`);
  });

Further suggestions: Since the table is the same element, You can define it once prior to the loop. And you can put the html directly instead of defining another variable (row).

MUHAMMAD ILYAS
  • 1,402
  • 7
  • 23
Ofir Baruch
  • 10,323
  • 2
  • 26
  • 39
0

Solution

let querySnapshot = [
  {
    Author: "A",
  },
  {
    Author: "B",
  },
  {
    Author: "C",
  },
  {
    Author: "D",
  },
  {
    Author: "A",
  },
  {
    Author: "B",
  },
  {
    Author: "C",
  },
  {
    Author: "A",
  },
];

let table = document.getElementById('myTable')
let allAuthers = querySnapshot
  .map(doc => doc.Author)
  .filter((value, index, self) => self.indexOf(value) === index);

allAuthers.forEach((auther) => {
  table.innerHTML += `<tr><td>${auther}</td></tr>`;
});
<table id="myTable"></table>
MUHAMMAD ILYAS
  • 1,402
  • 7
  • 23