0

I am a beginner in javascript and I was trying to find vowels in a given string using reduce function instead of filter or regex. When I added breakpoints to this function I see acc = 1 which shouldn't be the case. I am expecting output to be ['a', 'e', 'i'] but I get an error stating that acc.push is not a function because acc has been converted to an integer. Thanks.

function vowelReducer(str){
const vowels = ['a','e','i','o','u']
let inarr = [];
let arr = str.split('')
arr.reduce((acc, curr)=>{
  return vowels.indexOf(curr)> -1 ? acc.push('a') : acc
},inarr)
return inarr
}
vowelReducer('america')

Push in the above code gives length but in filter push works fine

function findVowels(str){
const vowels = ['a','e','i','o','u']
let inarr = [];
let arr = str.split('')
arr.filter((el)=>{
      return vowels.includes(el)?inarr.push(el):inarr
})
return inarr
}
findVowels('eola')
  • https://stackoverflow.com/questions/34259126/why-does-array-prototype-push-return-the-new-length-instead-of-something-more-us This answers the question. Use concat instead push. – Coding Croc May 21 '21 at 06:58
  • I misunderstood push. Array.prototype.push returns the length of array instead of mutated array – Coding Croc May 21 '21 at 07:00

0 Answers0