I need to iterate over an array of strings, count the occurrences of each string, and return a object with the value and the number of occurrences.
I’m trying to use the array reduce function to achieve such thing, but, despite the attempts, I haven’t been able to achieve that yet.
So I have the following:
["tony", "tony", "tony", "tony", "kassandra", "tony", "tony", "kassandra"]
I need the output:
[{ name: "tony", matches: 6 }, { name: "kassandra", matches: 2 }]
What should I use to obtain the above output?
I have tried the following:
const names = nameList.map((user) => user.name);
const reduce = names.reduce((p, c) => {
if (p == c) {
return { name: p, matches: `idk what put here yet` };
}
return c;
});
3
Answers
Firstly, count the occurrences of each name in the array.
Secondly, convert it into an object with the desired format of
name
and theirmatches
.If you want to use
.reduce()
approach to counting occurrences of names:Another approach to convert occurrences back into an object using
Object.entries()
Two approaches combined:
A pure
Array::reduce()
Typescript solution.We provide an aggregate object (
r
in the callback) where we store 2 values: the result arrayarr
with the desired output and a mapmap
where we can easily find an existing array items to increment found matches:A live typescript gist is here.
JS version:
And a benchmark:
To achieve the desired output, you can use the reduce function along with an object to store the counts of each name. Here’s an example of how you can implement it:
Output:
In the code above, the
reduce
function is used to iterate over thenameList
array. The accumulator (acc
) is an object that keeps track of the count for each name. If the current name (curr
) already exists as a property in the accumulator, the count is incremented by 1. Otherwise, a new property is created with the name as the key and an initial count of 1.After the
reduce
operation, we useObject.entries
to convert the object back into an array of key-value pairs. Then, we usemap
to transform each key-value pair into an object withname
andmatches
properties. Finally, the result is stored in theresult
variable.Note: In your attempted code, you were comparing
p
andc
using the equality operator (==
) which would only compare the values, not the count of occurrences. Additionally, you didn’t handle the case where the name is not equal to the previous one.