Home > Back-end >  Counting characters inside words using .map
Counting characters inside words using .map

Time:05-19

I'm having trouble with getting to the right answer, I'm currently in a course and I'm trying to make a sentance string that I input at the end (at console.log) count the characters for every word that I have, which means, if the sentence is " hey I'm mikey" then it will show [3, 2, 5] this is my code:

const IsstringArray = (StringsArray) => {
  return StringsArray.map(stringarraysplit => {
    stringarraysplit2 = stringarraysplit.split(" ")
    return stringarraysplit2.length
  })
}
console.log(IsstringArray(["hey my name is miki hey"]))

it shows the number of words, but I need the number of characters in those words.

CodePudding user response:

You can combine Array#map(), String#trim() and String#split()

Code:

const caractersByArray = a =>
  a.map(s =>
    s
      .trim()
      .split(' ')
      .map(s => s.length)
  )

const result = caractersByArray([
  "hey my name is miki hey", 
  " hey I'm mikey"
])

console.log(result)

CodePudding user response:

try this

const IsstringArray = (StringsArray) => {
    const stringarraysplit = StringsArray.split(" ")
    return stringarraysplit.map(stringarraysplit => { 
        return stringarraysplit.length;})
}  

console.log(IsstringArray("hey my name is miki hey"))    
  • Related