Stuck in a problem

This is the prompt:
Write a function that takes an array of strings
and returns a new string that consists of the final letters of each of the strings in the array

So for example:
stringFinalLetters([‘yoda’,‘anakin’, ‘skywalker’]);
should return ‘anr’

What am i doing wrong here if anyone could please elaborate?

function stringFinalLetters(arrayOfStrings)  {
  let emptyString = '';
  for (let i = 0; i < arrayOfStrings.length; i++) {
      let index = arrayOfStrings[i].length - 1;
      emptyString += arrayOfStrings[i][index];
  }
  return emptyString;
}
stringFinalLetters(['yoda','anakin', 'skywalker']);

If we log the returned result, everything looks fine. What exercise is this? Do you get an error?

oh jeez nevermind! Thanks though :smiley:

I tried to solve it by using reduce, but I can’t figure out why it’s not working.

const stringFinalLetters = (arr) => arr.reduce((acc,item) => acc.push( item[item.length - 1] ), [])

This gives error saying acc.push is not a function but why? Shouldn’t the value of acc be equal to the empty array in the last and push is a function on array. So what’s wrong?

according to reduce documentation:

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

an array is not a single value. So this can’t be. The single value could be a string, that might work

also, .push() adds to the array in memory, so has no return value. So that doesn’t work

R u sure?

I tried returning explicitly inside of reduce and it’s working now!

const stringFinalLetters = (arr) => arr.reduce((acc,item) => {
acc.push( item[item.length - 1] )
return acc
}, [])  

console.log(stringFinalLetters(['yoda','anakin', 'skywalker']))  // Output: ["a", "n", "r" ]

okay, maybe it is possible. But its not what the function is written for. Using something like .map() or .filter() is much more suitable.

1 Like

Gotcha! I just wanted to do it with reduce.