Home > Mobile >  Javascript - Count first element of multi dimensional array
Javascript - Count first element of multi dimensional array

Time:06-10

I have below code to extract the ID and username of a unique list of authors.

    let authorsList = await Poem.find({ 'author.id': {$nin: community.busAdmins}}).where('communities').equals(community._id).populate('authors').sort({"author.username": 1});

    let uniqueAuthorsList = [];
    authorsList.forEach(details => {
        if(!uniqueAuthorsList.some(code => code.username == details.author.username)){
            uniqueAuthorsList.push({username: details.author.username, id: details.author.id});
        }
    });

For each of those authors, I want to count how many blogs they have written. So far I have this code:

const counts = {};
        uniqueAuthorsList.forEach((el) => {
        counts[el] = counts[el] ? (counts[el]  = 1) : 1;
        });
        console.log(counts);

But this only returns:

{ '[object Object]': 7 }

How can I count the records using only the first element of the array (username), so I can return a list like this?

Dave: 4
Emily: 7
Mark: 2

CodePudding user response:

Put the counts in uniqueAuthorsList when you're creating it.

let uniqueAuthorsList = [];
authorsList.forEach(details => {
  let author = uniqueAuthorsList.find(code => code.username == details.author.username);
  if (author) {
    author.count  ;
  } else {
    uniqueAuthorsList.push({
      username: details.author.username,
      id: details.author.id,
      count: 1
    });
  }
});

You might want to just make uniqueAuthors an object rather than an array.

let uniqueAuthors = {};
authorsList.forEach(details => {
  if (uniqueAuthors[details.author.username]) {
    uniqueAuthors[details.author.username].count  ;
  } else {
    uniqueAuthors[details.author.username] = {
      username: details.author.username,
      id: details.author.id,
      count: 1
    };
  }
});
  • Related