-1

The output is correct with bracket notation while output is something else with dot notation

let data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 
'walk', 'car', 'van', 'car', 'truck', 'Pogo '];

    let instance_1 = data.reduce((acc, elm) => {
       if(!acc[elm]){
         acc[elm] = 0;
        }
       acc[elm]++;
       return acc;
     }, {})
      console.log(instance_1)
    
    let instance_2 = data.reduce((acc, elm) => {
       if(!acc.elm) {
           acc.elm = 0;
          }
       acc.elm++;
       return acc;
     }, {})
     console.log(instance_2);

Your help is much appreciated...

astroide
  • 807
  • 4
  • 16
  • 2
    `acc.elm` literally creates a property named `"elm"` so you have to use approach 1. Btw. you can simplify your reduce to `acc[elm] = (acc[elm] || 0) + 1; return acc;` – derpirscher Aug 29 '21 at 11:41
  • 3
    If the question is why `acc[elm]` works but `acc.elm` not, then the title is not correct -> [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"Write a title that summarizes the specific problem"_ – Andreas Aug 29 '21 at 11:43
  • Question is not clear. You say you have the correct output, and alternative that does not give the correct output, and then "Your help is much appreciated". What is the question? – trincot Aug 29 '21 at 13:56

3 Answers3

0

when accessing acc.elm you're referring to an element called elm in the javascript object acc.

this is equivalent to accessing acc["elm"].

So what you're doing in the second instance is accessing the same property for all elements.

for more info I'd suggest following this page

majdsalloum
  • 516
  • 1
  • 4
  • 17
0

In the first code, you are using acc[elm], which is getting the element of acc whose key is the value of elm. That code works in the expected way and counts how many of each element there is in the array.

In the second code, you are accessing acc.elm, which is getting the property named elm of acc. Since it always modifies the same property of acc (acc.elm), what your second reduce call will return is an object whose property named elm contains the number of elements in the array.

astroide
  • 807
  • 4
  • 16
0

In instance_2, you are creating a property "elm", by using dot notation. You use bracket notation when property identifiers have to be a String or a variable that references a String and dot notation when the property must be a valid JS identifier

For more details please read the documentation

J_K
  • 688
  • 5
  • 12