Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to console log pairs in array

For example I have this string "()[]|}" and I want to compare each characters with eachother, but first I can’t get the loop to work correctly. For the first log it works correctly, but after instead of going +1 it should go +2 I believe so it doesn’t start from ). How do can I do this properly?

function isValid(s) {
    
  let temp = s.split("");

  for (let i = 0; i < s.length/2; i++) {
        console.log(temp[i], temp[i+1]);
  }
};

isValid("()[]|}");

I want to log this

( )
[ ]
| }

not

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

( )
) [
[ ]

>Solution :

Your code is correct but your for loop is slightly off:

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

Loop while i is less than the length, but add 2 instead of 1.

function isValid(s) {
    
  let temp = s.split("");

  for (let i = 0; i < s.length; i += 2) {
        console.log(temp[i], temp[i+1]);
  }
};

isValid("()[]|}");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading