How to replace numbers with words via map?
-
I have a string of numbers - '80 75 60 90 '. I need to replace them with words with a certain condition: if the number is in the range of 50-100, then replace it with the word "First", for a number from 30 to 50 by "Second", for a number from 10 to 30 by "Third". It also needs to be implemented via map.
I've tried doing it myself, but it only outputs commas.
var str = '80 75 85 90'; var arr1 = str.split(' '); var doubles = arr1.map(function(arr1) { for(var i=0; i < arr1.length; i++) { if(arr1[i]>=50 && arr1[i]<=100) { arr1[i]="Первый"; } if(arr1[i]>=30 && arr1[i]<=50) { arr1[i]="Второй"; } if(arr1[i]>=10 && arr1[i]<=30) { arr1[i]="Третий"; } } }); alert(doubles);
JavaScript Anonymous, Dec 17, 2020 -
function replacer(string, expression, mapper) {
return (string.match(expression) || []).map(mapper);
}
function match(rawNumber) {
let number = parseInt(rawNumber);
if (number >= 10 && number < 30) {
return 'Третий';
} else if (number >= 30 && number < 50) {
return 'Второй';
} else if (number >= 50 && number < 100) {
return 'Первый';
} else {
return 'Что-то';
}
}
console.log(replacer('80 75 85 90 10 30 0', /\d+/g, match));
// ['Первый', 'Первый', 'Первый', 'Первый', 'Третий', 'Второй', 'Что-то']Anonymous -
var str = '80 25 85 90';
var strArr = str.split(' ');
var res = strArr.map((item)=>{
console.log(item);
if(item >= 50 && item <=100){
item = "First";
}
else if(item >= 30 && item <= 50){
item ="Second";
}
else if(item >=10 && item <= 30){
item ="Third";
}
return item;
});
console.log(res);Phoebe Moreno -
var str = '5 80 75 30 85 90 10 30 0';
var out= str.split(/ /).map(n=>(n=+n,n<10?`${n}`:n<30?'Третий':n<50?'Второй':n<100?'Первый':`${n}`)).join(' ');
console.log(out); // 5 Первый Первый Второй Первый Первый Третий Второй 0Anonymous
3 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!