I am trying to convert a string like “sheep” into an object like this:
JavaScript
x
19
19
1
{
2
"s":{
3
"initial":1,
4
"final":1
5
},
6
"h":{
7
"initial":1,
8
"final":1
9
},
10
"e":{
11
"initial":2,
12
"final":2
13
},
14
"p":{
15
"initial":1,
16
"final":1
17
}
18
}
19
Currently I can use reduce method in javascript and achive this:
JavaScript
1
5
1
const names = 'sheep'.split('');
2
const count = (names) =>
3
names.reduce((acc, name) => ({ acc, [name]: (acc[name] || 0) + 1 }), {});
4
console.log(count(names)) //{ s: 1, h: 1, e: 2, p: 1 }
5
I have tried to read similar posts but I am pretty new to JS. Can anyone please help me? Thanks.
Advertisement
Answer
Try like this
JavaScript
1
13
13
1
const names = "sheep".split("");
2
const count = (names) =>
3
names.reduce(
4
(acc, name) => ({
5
acc,
6
[name]: {
7
initial: (acc?.[name]?.initial ?? 0) + 1,
8
final: (acc?.[name]?.final ?? 0) + 1,
9
},
10
}),
11
{}
12
);
13
console.log(count(names));