Replacing all found items Items using splice

Viewed 99

So I want to find all items that match a string and replace them. For some reason, I can't get it to iterate and replace all. Any help would be appreciated

const word = ['h', 'e', 'l', 'l', 'o'];
var placeholder = word.map(e => {
  return "*"
});

let letter = 'l';

word.forEach(e => {
  if (e === letter) {
    placeholder.splice(word.indexOf(letter), 1, letter);
  }
});


console.log(placeholder);

2 Answers

Use the index parameter in the callback to forEach instead of always using the first index at which the letter is found.

const word = ['h', 'e', 'l', 'l', 'o'];
var placeholder = word.map(e => {
  return "*"
});

let letter = 'l';

word.forEach((e,i) => {
  if (e === letter) {
    placeholder.splice(i, 1, letter);
  }
});


console.log(placeholder);

Directly using map is much simpler.

const word = ['h', 'e', 'l', 'l', 'o'];
let letter = 'l';
const res = word.map(e => letter === e ? letter: "*");
console.log(res);

Note that my answer isn't the most efficient... rather I wanted to explain why your function wasn't working and how you would have to edit it to make that approach work...

Your word.forEach function replaces the same letter in placeholder twice because Array.indexOf() always returns the index of the 1st occurrence... and you never update word.. you only update placeholder. You will need to make a copy of word and make changes to it as well...

const word = ['h', 'e', 'l', 'l', 'o'];
let tempWord = JSON.parse(JSON.stringify(word));
var placeholder = word.map(e => {
  return "*"
});

let letter = 'l';

tempWord.forEach(e => {
  if (e === letter) {
    placeholder.splice(tempWord.indexOf(letter), 1, letter);
    tempWord.splice(tempWord.indexOf(letter), 1, '*');    
  }
});


console.log(placeholder);

Related