how to loop through two indexes in javascript

Viewed 87

why it's giving me the first index and i need the ouput below which is "StOp mAkInG SpOnGeBoB MeMeS!"

 function spongeMeme(sentence) {
  let x = sentence.split("");
  for(let i = 0; i < sentence.length;i+=2){
    return x[i].toUpperCase()
  }
}
console.log(spongeMeme("stop Making spongebob Memes!")) // S

// output : StOp mAkInG SpOnGeBoB MeMeS!"
4 Answers

Try this:

        function spongeMeme(sentence) {
        let x = sentence.split("");
        let newSentence = '';
        for(let i = 0; i < sentence.length;i++){
            // If the letter is even
            if(i % 2 ==0) {
                newSentence += x[i].toUpperCase();
            } 
            // If the letter is odd
            else {
                newSentence += x[i].toLowerCase();
            }
        }
        return newSentence
      }
      console.log(spongeMeme("stop Making spongebob Memes!"))

First of all you can only return once per function, so you have to create a variable and store all the new letter inside, and, at the end, return this variable.

You're returning just the first letter of what is stored inside of x. Try to debug it and see what is going on.

The way I'd do it is like so:

function spongeMeme(sentence) {
return sentence.split("")
.map((s, i) => (i % 2 != 0 ? s.toUpperCase() : s))
.join("");
}
console.log(spongeMeme("stop Making spongebob Memes!"));

You're immediately returning on the first iteration of your for loop, hence the reason you're only getting back a single letter.

Let's start by fixing your existing code:

function spongeMeme(sentence) {
  let x = sentence.split("");

  for(let i = 0; i < sentence.length; i+=2) {

    // You can't return here. Update the value instead.
    return x[i].toUpperCase()
  }

  // Join your sentence back together before returning.
  return x.join("");
}

console.log(spongeMeme("stop Making spongebob Memes!"))

That'll work, but we can clean it up. How? By making it more declarative with map.

function spongeMeme(sentence) {
  return sentence
    .split('') // convert sentence to an array
    .map((char, i) => { // update every other value
      return (i % 2 === 0) ? char.toUpperCase() : char.toLowerCase(); 
    })
    .join(''); // convert back to a string
}

You can also do that:

const spongeMeme = (()=>
  {
  const UpperLower = [ (l)=>l.toUpperCase(),  (l)=>l.toLowerCase() ]

  return (sentence) =>
    {
    let i = -1, s = ''
    for (l of sentence) s += UpperLower[i=++i&1](l)
    return s
    }
  })()

console.log(spongeMeme("stop Making spongebob Memes!"))
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

OR

function spongeMemez(sentence)
  {
  let t = false, s = ''
  for (l of sentence) s += (t=!t) ? l.toUpperCase() : l.toLowerCase()
  return s
  }

but I think this version is slower, because using an index should be faster than a ternary expression

Related