1

I'm trying to make some sort of cryptographer, and I need to replace for ex. every "a" with "b" when the user asks for it.

if (DoYouWannaCrypt == 1) {
  binput.forEach(function(v, i) {
    if(v === "a") {
      input[i] = "$"
    }
  })
};

This works fine, however I want to add another condition that this should only be done for all 5th values of another array.

if (Val is 5th) {
  if (DoYouWannaCrypt == 1){
    binput.forEach(function(v, i) {
      if(v === "a") {
        input[i] = "$"
      }
    })
  }
};

I think you can see where I'm stuck at. I need it to work for all 5th values not just the first one.

6
  • 1
    Please don't use <br> as new lines. Use the markdown to style your post. Commented Apr 20, 2017 at 21:10
  • 2
    why not ask if i can be evenly divided by 5? syntax is if(i % 5 == 0) Commented Apr 20, 2017 at 21:11
  • 1
    No, I can't see where you're stuck at. What is Val? If binput is your array, your if is in the wrong place. Commented Apr 20, 2017 at 21:11
  • Please read this before posting other posts: stackoverflow.com/help/formatting Commented Apr 20, 2017 at 21:13
  • ABove abstraction of the code should work. If something doesn't work, error is probably in your abstraction: (Val is 5th) and we can't see it. Maybe you should post a fiddle Commented Apr 20, 2017 at 21:13

2 Answers 2

2

Thats what map is for:

var crypted=binput.map((l,i)=>(i+1)%5?l:({"a":"$"}[l]||l));

http://jsbin.com/zepewituro/edit?console

Check if index (starting from 0, thats why +1 ) modulo 5 is not 0,then take the letter l, if its 0 ( then we are at the 5*n th position), then we try to replace our letter with another one, if it isnt possible fallback to the letter (||l).

Sign up to request clarification or add additional context in comments.

1 Comment

OP didn’t say “for every fifth element of binput”, he said “for every fifth element of another array”.
1

Since your code appears irrelevant to your problem, let me store it safely in a function first:

function something(binput, input, DoYouWannaCrypt) {
  if (DoYouWannaCrypt == 1)
    binput.forEach(function(v, i) {if (v === "a") input[i] = "$"});
}

If you want to do this operation only for the first element of anotherArray:

for (let Val in anotherArray)
  if (!Val) something(binput, input, DoYouWannaCrypt);

If you want to do it for every element of anotherArray:

for (let Val in anotherArray)
  something(binput, input, DoYouWannaCrypt);

If you want to do it for every fifth element of anotherArray:

for (let Val in anotherArray)
  if (!(Val%5)) something(binput, input, DoYouWannaCrypt);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.