I have array of object with few words I want to know occurance of each word and push into key value pair format
let words = ["aabbbc", "dddeeef", "gghhhii"]
Output
[{a:2, b:3,c:1}, {d:3,e:3,f:1}, {g:2,h:3:i:2}]
CodePudding user response:
let words = ["aabbbc", "dddeeef", "gghhhii"]
const occurences = (w) => {
const obj = {};
for (const c of w) {
if (obj[c] === undefined) obj[c] = 0;
obj[c] ;
}
return obj;
}
const arr = words.map(w => occurences(w));
console.log(arr)
CodePudding user response:
This is a classic map
and reduce
task where one maps the array of strings and for each string creates the character-specific counter-statistics while reducing the string's character-sequence (...split('').reduce( ... )
) and by programmatically building an object which counts/totals each character's occurrence.
console.log(
["aabbbc", "dddeeef", "gghhhii"]
.map(string =>
string
.split('')
.reduce((result, char) => {
result[char] = (result[char] ?? 0) 1;
return result;
}, {})
)
)
// [{a:2, b:3,c:1}, {d:3,e:3,f:1}, {g:2,h:3:i:2}]
.as-console-wrapper { min-height: 100%!important; top: 0; }
CodePudding user response:
let words = ["aabbbc", "ddeeef", "ghhhii"]
let newArr = []
words.forEach((e,index)=>{
e.split('').forEach(n=>{
if(!newArr[index]){
newArr[index]={}
}
if(!newArr[index][n]){
newArr[index][n]=0
}
(newArr[index][n]>=0) && newArr[index][n]
})
})
CodePudding user response:
Trying to keep it easy and readable:
const words = ['aabbbc', 'dddeeef', 'gghhhii']
const output = []
for (const word of words) {
const result = {}
for (const letter of word) {
result[letter] = result[letter] || 0
result[letter]
}
output.push(result)
}
console.log({ output })