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:
I'm always looking but I can't find the right approach.
Does anyone have any idea what soultion is? Thank you in advance
Simpler:
const codeLetter = "p";
const specialLetter = "o";
const transform = input => input.split(specialLetter).join(specialLetter+codeLetter)
console.log(transform("Hello World"));