S
S
Stanislav Ponomarev2020-04-08 09:12:24
JavaScript
Stanislav Ponomarev, 2020-04-08 09:12:24

Any other options to replace if in map?

People, it is possible to replace if with something else, in this code

const characters = [
  'Люк Скайуокер',
  'Оби Ван',
  'Чубакка',
  'Энакин Скайуокер',
  'Хан Соло',
  'Палпатин'
];

const newCharacters = characters.map(function (character) {
  if (character === 'Энакин Скайуокер') {
    return 'Дарт Вейдер';
  }

  return character;
});

console.log(newCharacters);


Tried through slice and splice does not work. Maybe I'm doing it wrong. Is it possible to do it through the slice and splice methods?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-04-08
@Chelentano93

return character === '...' ? '...' : character;
Or, if there are several replacements, make an object where it will be indicated who should be replaced with whom:

const replacements = {
  '...': '...',
  '...': '...',
  ...
};

const newCharacters = characters.map(n => replacements[n] || n);

S
Stepan Krapivin, 2020-04-08
@xevin

Using splice

let characters = [
  'Люк Скайуокер',
  'Оби Ван',
  'Чубакка',
  'Энакин Скайуокер',
  'Хан Соло',
  'Палпатин'
];

const enakinIndex = characters.indexOf('Энакин Скайуокер')

characters.splice(enakinIndex, 1, 'Дарт Вейдер')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question