0
  1. I run the code but find that I have to use cal[item] to put the item in array inside the object. Why the old ways cal.item doesn't work?
  2. I tried using "if + else" like below and using "if" only, the result are different, the "if" version gives me the correct answer. But I don't see why it causes different flow in calculation.

Thank you for your help in advance.

const number = "3 5 30 31 43 48 2 11 13 45 46 49 11 14 21 28 37 44 18 29 32 33 36 40 2 20 24 30 32 46 5 17 35 37 42 49 1 24 25 27 31 37 15 17 29 30 34 37 5 10 18 20 28 33 1 22 25 27 31 36"
const array = number.split(" ")
const cal = {}
for (const item of array){
    if(cal.item == null){
        cal.item = 0
    }else{
        cal.item += 1;
    }
}
console.log(cal)
Ele
  • 33,468
  • 7
  • 37
  • 75
Edith
  • 95
  • 5
  • 2
    If `item` is a variable containing text, and you want to set a property based on that text, you need to use `cal[item]` because `cal.item` will set the `.item` property. This isn't "the old way", it's just how square brackets / dot notation works (and has always worked). As for your second question, since you're using the wrong `cal.item`, it'll start out being `undefined`, then be defined during the next iteration. –  Sep 10 '20 at 16:30
  • I think you need to clarify your intent/desire here `cal.item` is the same as `cal["item"]` as a reference to the object property. – Mark Schultheiss Sep 10 '20 at 16:35
  • `array.includes(113)` will will tell you if it is included https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes as it returns a boolean – Mark Schultheiss Sep 10 '20 at 16:37
  • If the duplicate does not answer your question, please clarify with a detailed edit of the question and ask to have it reopened. – Mark Schultheiss Sep 10 '20 at 17:47
  • Thanks, and Im tryna ask why using "if" only will give me correct answer, like "{37:4}" but "if-else" above gives me"{37:3}"? – Edith Sep 11 '20 at 14:03
  • I mean even if I put cal[item] right, this still happens. – Edith Sep 11 '20 at 14:16

1 Answers1

0

You could use reduce to achieve that

const number =
  "3 5 30 31 43 48 2 11 13 45 46 49 11 14 21 28 37 44 18 29 32 33 36 40 2 20 24 30 32 46 5 17 35 37 42 49 1 24 25 27 31 37 15 17 29 30 34 37 5 10 18 20 28 33 1 22 25 27 31 36"

const array = number.split(" ")

const occurrences = array.reduce((acc, el) => {
  acc[el] = (acc[el] || 0) + 1
  return acc
}, {})

console.log(occurrences)
hgb123
  • 13,869
  • 3
  • 20
  • 38