0

I've got an example array that I'm trying to reduce by the counts of the occurrence of a key (sentiment in this example):

const sentimentLog = [
  {
    id: 1,
    createdOn: new Date('2020-02-13'),
    sentiment: 1
  },
  {
    id: 2,
    createdOn: new Date('2020-02-12'),
    sentiment: 1
  },
  {
    id: 3,
    createdOn: new Date('2020-02-12'),
    sentiment: 2
  },
  {
    id: 4,
    createdOn: new Date('2020-02-11'),
    sentiment: 3
  },
  {
    id: 5,
    createdOn: new Date('2020-02-11'),
    sentiment: 2
  },
  {
    id: 6,
    createdOn: new Date('2020-02-10'),
    sentiment: 1
  },
  {
    id: 7,
    createdOn: new Date('2020-02-10'),
    sentiment: 2
  },
  {
    id: 8,
    createdOn: new Date('2020-02-09'),
    sentiment: 1
  }
]

I'm using:

const sentimentGrouped = (sentiments) => {
  return sentiments.reduce((hash, { sentiment }) => {
    hash[sentiment] = (hash[sentiment] || 0) + 1
    return hash
  }, [])
}

And it's nearly there. What I can't figure out is how to replace undefined when there's no sentiment scores of 0 (which is a possibility).

console.log('sentimentGrouped', sentimentGrouped(sentimentLog))

The above produces:

"sentimentGrouped" [undefined, 4, 3, 1]

Whereas I'd like:

"sentimentGrouped" [0, 4, 3, 1]

What am I missing?

Thanks in advance.

Edit: I'll elaborate a bit further, there's 4 scores that will be returned (0 to 3). The data returned will be based on a date range. So there may be instances where there'll be no 1s returned, similarly no 3s returned by a different date range.

4
  • 1
    Is there a maximum sentiment value? Wondering if you can prefill the array with all zeros. Commented Feb 14, 2020 at 15:03
  • It's between 0 and 3 - so 4 options only - the UI represents these as smiley faces :) Commented Feb 14, 2020 at 15:04
  • beside pre populate the array with zeros (as you know the length of it in advance) is there a problem using an object as the hash? Commented Feb 14, 2020 at 15:08
  • I want to avoid an object, as I'm using the result within a v-for loop in Vue.js Commented Feb 14, 2020 at 15:09

1 Answer 1

4

The issue is that if you never touch an element of the array, then it stays as a hole in the array, which means it's treated as undefined. Since you know the length of the array i would just prefill the array with zeros. Any sentiment score that does occur will be incremented. Any one that doesn't will stay with its initial value.

return sentiments.reduce((hash, { sentiment }) => {
  hash[sentiment] = hash[sentiment] + 1
  return hash
}, [0, 0, 0, 0])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.