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

98 thoughts on “Insert an element in array after a specific value and only if this value respect a condition || Javascript”

  1. Superb blog! Do you have any recommendations for aspiring writers?
    I’m planning to start my own site soon but I’m a little lost on everything.
    Would you suggest starting with a free platform like WordPress or
    go for a paid option? There are so many options out there that I’m completely confused ..
    Any ideas? Thanks! http://droga5.net/

    Reply

Leave a Comment