+ 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])
3 Antworten
+ 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"])
+ 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]);
+ 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]