Array.map returns empy array

Hi! I have an array of objs in which objs are retrived from a Firestore DB and then pushed into the array.

So far no problems.

Then i’m trying to console.log every element, with this code

console.log(highscoresArray.map(highscore => {
    return `${highscore.username}: ${highscore.score}`;
}));

But it returns an empty array. Whta’s wrong with it?

My guess is highscoresArray is an empty array. To test this theory, put the following on the line above your code:

console.log(highscoresArray);

What does the above show? Do you get an error in the browser console?

No error, this is a part of the array content

0: {score: 30, username: "Ada"}
1: {score: 0, username: "Gianni"}
2: {score: 30, username: "Ada"}
3: {score: 30, username: "Ada"}

Without seeing your full code, all I can tell you is if I create an array like the following and run the code, I do not get an empty array:

var highscoresArray = [
  {username: 'RandellDawson', score: 10},
  {username: 'Antoder10', score: 20}
];

console.log(highscoresArray.map(highscore => {
    return `${highscore.username}: ${highscore.score}`;
}));

image

What value do you show if you put this before your existing console.log statement?

console.log(highscoresArray instanceof Array);

You can check here.

Click on show highscores

Seems fine, it returns true

Put your code after the following section (within the then callback function).

querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        //console.log(doc.id, " => ", doc.data());
        highscoresArray.push(doc.data());
        //HIGHSCORE_USERNAME_TEXT.innerHTML = doc.data().username;
    });

The firestore.collection(COLLECTION_NAME).get() is an asynchronous call. The data will not readily be available outside this code block.

1 Like

Thank you! Now everything works fine