const obj1 = {
1: 'a',
2: 'b',
3: 'a',
4: 'c',
5: 'a',
6: 'd',
7: 'c',
};
For the above code I need to get output as below
output = { a: 3, b: 1, c: 2, d: 1 }
const obj1 = {
1: 'a',
2: 'b',
3: 'a',
4: 'c',
5: 'a',
6: 'd',
7: 'c',
};
For the above code I need to get output as below
output = { a: 3, b: 1, c: 2, d: 1 }
2
Answers
this function works
A concise / advanced solution would look like this:
Object.values()
gives you the values of an object (see documentation).Array.protoype.reduce()
is a function which takes a function as its argument. Because we want to start on an empty object, we give it{}
as a second input parameter. The reduce function iterates over all given array values and applying the given function to it. The result is a single value opposed to whatArray.prototype.map
does.(see documentation)
For read-/memorability reasons I choose the parameter names
o
for old andn
for new for the reduce function.What we are doing here is simple:
{}
) exists a key ofn
(n
isa
in the first step). If not give it a count of0
.o[n]
.o
As you see the
o
is passed in and back the function and it accumulates the count. So this part is often calledaccumulator
. But I useo
because old is easier for me to remember than accumulator.Functions like
Array.prototype.map
andArray.protoype.reduce
( and don’t forgetArray.protoype.reduceRight
) are hard to understand at first. But once understood they will be the best tools on your belt.