+ 1

reduce method problem

i learned that name[ i ] i is the index we cant pass string name alice or bob inside the square bracket why allNames[ name ] name is the current value 'Alice' so on var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; var countedNames = names.reduce(function (allNames, name) { if (name in allNames) { allNames[name]= allNames[name]+1; }else { allNames[name] = 1; } return allNames; }, {}); console.log(countedNames) console.log(names[0])

2nd Feb 2019, 12:37 PM
Danielov
Danielov - avatar
3 Respostas
+ 6
It's possible for allNames in the above code, to be a dictionary, where elements are stored as key-value pairs. var dict = { "one": 1, "two": 2 }; The values can then be accessed using keys: console.log(dict["one"])
2nd Feb 2019, 1:00 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
I'm sorry, I don't know English well, and I didn't understand your question ... But your code works) Instead of "console.log(countedNames)" write this: for (let i in countedNames)      console.log (i + ": " + countedNames [i]);
2nd Feb 2019, 1:09 PM
Игорь Яковенко
Игорь Яковенко - avatar
+ 1
Hatsy Rei so the initial value dictionary and the name considered as key is that the reason we can pass name key inside allNames and increment allNames[name]
3rd Feb 2019, 4:56 AM
Danielov
Danielov - avatar