3

I've been working for a while on this function but i cannot figure out why even if I'm using .splice() I don't get a modified array. I'm providing the index at which to start changing the array "i", the number of elements to remove "1" and the element to add "str[i]".

function wave(str) {
  let result = [];
  for (let i = 0; i < str.length; i++) {
    if ((/[a-z]/ig).test(str[i])) {
      let st = str.split("").splice(i, 1 , str[i].toUpperCase());
      result.push(st);
    }
  }
 return result;

}


console.log(wave('hello')); // expected ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
console.log(wave("two words")); // ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
Mugg84
  • 585
  • 1
  • 7
  • 15
  • 2
    You might want to join the split string, otherwise it will stay an array. – evolutionxbox Jan 21 '20 at 14:54
  • [There's](https://stackoverflow.com/a/59843765/11299053) a bit [faster](https://jsperf.com/oiuweroiuzxfljk/1) and shorter way to achieve your goal with high-order methods, just in case... – Yevhen Horbunkov Jan 21 '20 at 15:08

1 Answers1

7

Array#splice returns the removed item/s. You need to keep the array - and remove and add the new item.

The regular expression does not need to be wrapped with parenthesis for accessing the RegExp#test method.

Before pushing to array, you need to take Array#join for getting a single string.

function wave(str) {
    let result = [];
    for (let i = 0; i < str.length; i++) {
        if (/[a-z]/ig.test(str[i])) {
            let st = str.split("");
            st.splice(i, 1, str[i].toUpperCase());
            result.push(st.join(''));
        }
    }
    return result;
}

console.log(wave('hello')); // expected ["Hello", "hEllo", "heLlo", "helLo", "hellO"];
console.log(wave("two words")); // ["Two words", "tWo words", "twO words", "two Words", "two wOrds", "two woRds", "two worDs", "two wordS"];
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    Thanks for your help. I couldn't figure out why the reason why only the deleted character was returned. And for pointing out that i don't need to wrap my expression for the regex. I've just started using them so I'm not too confident yet. – Mugg84 Jan 21 '20 at 15:19
  • @Mugg84 : *'...why only deleted'* it's just the way `splice()` method works - it edits array in place and returns deleted portion of it only (read through the docs for comprehensive reference); *'...don't need to wrap'* - regexp is not needed here at all, moreover it drags down your code performance. – Yevhen Horbunkov Jan 21 '20 at 15:43