Answer the question
In order to leave comments, you need to log in
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);
Answer the question
In order to leave comments, you need to log in
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);
Using splice
let characters = [
'Люк Скайуокер',
'Оби Ван',
'Чубакка',
'Энакин Скайуокер',
'Хан Соло',
'Палпатин'
];
const enakinIndex = characters.indexOf('Энакин Скайуокер')
characters.splice(enakinIndex, 1, 'Дарт Вейдер')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question