[Vuejs]-JS matching strings from different arrays

1👍

I think you’re aiming for something like this:

// Mock data
const users = [
  { metadata: { creationTime: '3 apr' } },
  { metadata: { creationTime: '7 apr' } },
  { metadata: { creationTime: '26 jan' } },
  { metadata: { creationTime: '4 feb' } },
  { metadata: { creationTime: '9 dec' } },
  { metadata: { creationTime: '25 dec' } },
  { metadata: { creationTime: '9 apr' } }
]

// Months in lower-case... creationTime is assumed to also use lower-case
const months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']

// Use `map` to create an array the same length as `months`
const counts = months.map(month => {
  let count = 0
  
  // Loop over the `users` array, note the use of `of`, not `in`
  for (const user of users) {
    // Using `includes` is somewhat crude but may work depending on how
    // creationTime is formatted. It's no worse than indexOf
    if (user.metadata.creationTime.includes(month)) {
      ++count
    }
  }
  
  return count
})

console.log('Counts: ' + counts.join(' '))

The output in this case is an array containing the counts for each month but you could easily adapt the return value inside the map function to return an object with the month name and count if that’d be easier to work with.

As I noted in the comments the main flaw in your original code is the use of for (var month in months) {. That will iterate over the numeric indices rather than the month names, so you’re just checking for 0, 1, 2, etc. rather than jan, feb, mar, etc.. To iterate over the contents of the array you would need to use a for/of loop instead.

Leave a comment