0

I have a function that is meant to do this:

accum("abcd");    // "A-Bb-Ccc-Dddd"
accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"

We can see the first "for" loop repeats each substring by it's current (index + 1). It pushes it to the array and the output would be [ 'a', 'bb', 'ccc', 'dddd' ]

It is then obvious that I need to iterate over this array and capitalise each string which I have done by the second for loop below. The problem is when I return the array it is returning like this: [ 'A', 'B', 'C', 'D' ]

It is returning the first substring of each string but it isn't returning the rest of them.

function accum(s) {
    var splitstring = s.split("")
    var newarray = []
    for(var i = 0; i < splitstring.length; i++) {
        newarray.push(splitstring[i].repeat(i + 1))
    }
    for (var i = 0; i < newarray.length; i++) {
        newarray[i]  = newarray[i].charAt(0).toUpperCase()    
    }
    return newarray
}
accum("abcd")
A.A Noman
  • 5,244
  • 9
  • 24
  • 46
monkeybanana
  • 27
  • 1
  • 6
  • 1
    You are overwriting the whole string in your second loop. Take a look at [this](https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) to see how to do it. – Federico klez Culloca Dec 04 '17 at 16:06
  • 1
    ` newarray[i] = newarray[i].charAt(0).toUpperCase() ` <-- well that seems to be your problem since you replace it with just the first character. – epascarello Dec 04 '17 at 16:08

2 Answers2

3

That's because you're overwriting the string with only the first character. you need to concatenate the rest of the string.

  for (var i = 0; i < newarray.length; i++) {
    newarray[i]  = newarray[i].charAt(0).toUpperCase() + newarray[i].slice(1);
  }

Here's a shorter version of your code:

function accum(s) {
  return s.split("").map((ss, i) => ss.toUpperCase() + ss.repeat(i)).join("-");
}

console.log(accum("abcd"));

It also adds the separator that you seem to want. If you actually wanted the array, then remove .join("-").

0

No need to use second for loop. Just use map() on the returned array.

function accum(s) {
  var splitstring = s.split("");
  var newarray = [];
  for(var i= 0; i < splitstring.length; i++) {
    newarray.push(splitstring[i].repeat(i + 1))
  }
  return newarray.map(j=>j[0].toUpperCase()+ j.slice(1)).join('-');
}

console.log(accum("abcd"));
Mamun
  • 66,969
  • 9
  • 47
  • 59