Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
How to create a reusable array.reduce function

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
    },{})

}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!