Im working on solving an Anagram problem wanted to get clever with Javascript methods
here is my code
const stringA = ["hello"]
const stringB = ["olhle"]
let cleanStrA = stringA.replace(/[^\w]/g, '').toLowerCase().split('')
let cleanStrB = stringB.replace(/[^\w]/g, '').toLowerCase().split('')
function charMap (str) {
str.reduce((acc, cur) => {
acc[cur] = acc[cur] + 1 || 1
return acc
},{})
return str
}
let buildCharMapA = charMap(cleanStrA)
let buildCharMapB = charMap(cleanStrB)
console.log(buildCharMapA)
result = ("hello")
When i console log this it returns the original array, but when i remove the function encompassing the reduce method it create the intended object
let reduceFn = cleanStrA.reduce((acc, cur) => {
acc[cur] = acc[cur] + 1 || 1
return acc
},{})
console.log(reduceFn)
result = {h:1, e:1, etc.}
What gives?
As the comments pointed out i mistakenly returned str instead of the entire reduce function
function charMap (str) {
return str.reduce((acc, cur) => {
acc[cur] = acc[cur] + 1 || 1
return acc
},{})
}