Search code examples
javascriptarrayssplice

Insert an element in array after a specific value and only if this value respect a condition || Javascript


I looked for a solution in the many other requests I could consult on the site but either it doesn't really correspond to what I want to do or the language is different.

Here is my problem: I would like to add a particular value in an array if the condition is valid.

For example:

If a string is entered (e.g. "Hello World"), I would like the letter 'p' to be inserted after the letter 'o'. It would then give the output of the function: "Hellop Woprld".

Here is my current approach :

function transform(input) {
  const inputArray = input.split('');
  const codeLetter = 'p';

  inputArray.map((inputEl, i) => {
    if (inputEl === 'o') {
      inputArray.splice(inputEl[i+1], 0, codeLetter)
    } else {
      return inputArray;
    }
  });
  return inputArray;
}
console.log(transform("Hello World"));

And here is the resulting output:

[
  'p', 'p', 'p', 'p', 'p',
  'p', 'p', 'H', 'e', 'l',
  'l', 'o', ' ', 'W', 'o',
  'r', 'l', 'd'
]

Two problems are open to me:

  1. My approach concerning the iteration of the letter 'p' is wrong
  2. the elements are added at the beginning of the table and not after the letter 'o'.

I'm always looking but I can't find the right approach.

Does anyone have any idea what soultion is? Thank you in advance


Solution

  • Simpler:

    const codeLetter = "p";
    const specialLetter = "o";
    const transform = input => input.split(specialLetter).join(specialLetter+codeLetter)
    
    console.log(transform("Hello World"));