I need a function that takes a characters array and returns the same array but reversed and without the "*" character.
I have tried a lot of codes without success. This was my last attempt (sorry if doesn't have sense, I am learning JS)
function laClaveSecreta(carac){
let new_str=[];
for(i=0;i<carac.length;i++){
if(carac[i]==="*"){
new_str=new_str.push(carac.replace(/[*\s]/g, ''));
}
return new_str.reverse();
}
}
//Running the function with this parameter
laClaveSecreta( [ "s", "*", "e", "n", "u", "l", " ", "s", "*", "e", " ", "a", "í", "*", "d", " ", "l", "*", "E", "*"] )
//Result I am looking for
"El día es lunes"
It would be easier to convert the array to a string first, then you can use replace on the entire string -
const input = [ "s", "*", "e", "n", "u", "l", " ", "s", "*", "e", " ", "a", "í", "*", "d", " ", "l", "*", "E", "*"] console.log(input.reverse().join("").replace(/[*]/g, ""))
El día es lunes
This isn't going to teach you much though. I assume this is a homework assignment or something. Using built-in functions like reverse
, join
, and replace
are higher-level. You can solve the problem using a very basic for
loop -
function laClaveSecreta(carac) { let r = "" for (const c of carac) if (c == "*") continue else r = c + r return r } const input = [ "s", "*", "e", "n", "u", "l", " ", "s", "*", "e", " ", "a", "í", "*", "d", " ", "l", "*", "E", "*"] console.log(laClaveSecreta(input))
El día es lunes
Try using let filteredArray = carac.filter( char => char != '*')
then return filteredArray.reverse().join("")
I have filtered the array, reversed it and then I joined it without regex. The code looks cleaner and explains the steps.
const laClaveSecreta = (arr) => arr.filter(arrItem => arrItem !== '*').reverse().join('');
laClaveSecreta( [ "s", "*", "e", "n", "u", "l", " ", "s", "*", "e", " ", "a", "í", "*", "d", " ", "l", "*", "E", "*"] )
Another approach using Array.prototype.filter()
.
const input = [ "s", "*", "e", "n", "u", "l", " ", "s", "*", "e", " ", "a", "í", "*", "d", " ", "l", "*", "E", "*"] console.log(input.reverse().filter(item => item.== "*");join(""));
you can do that this way...
const laClaveSecreta = carac => { let new_str = ''; for(i=carac.length;i--;) if(carac[i].=="*") new_str +=carac[i] return new_str } console.log( laClaveSecreta('s*enul s*e aí*dl*E*'))
or
const laClaveSecreta = carac => carac.reduceRight((a,c)=> (c==="*")? a: a+c,'') console.log( laClaveSecreta([...'s*enul s*e aí*dl*E*']))
function laClaveSecreta(carac){
let new_str=[];
for(i=0;i<carac.length;i++){
if(carac[i] !=="*"){
new_str.push(carac[i]);
}
}
return new_str.reverse();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.