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

Convert string into variable in array automatically

I have a problem when I\m trying to convert a string to a variable in an array.

The variables are:

const n = 1; const s = -1;

The array string:

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

let walk = ['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 'n']; 

I want to convert automatically to this variable array:

let walk = [n, s, n, s, n, s, n, s, n, n];

I’m trying to split but the array still string not a var:

let text = walks.toString().split(',').join('-')
console.log(text)

>Solution :

You could put s and n into an object.

const variables = {
  n: 1,
  s: -1
};

let walk = ['n', 's', 'n', 's', 'n', 's', 'n', 's', 'n', 'n'];

console.log(
  walk.map(variable => variables[variable])
)

See this question for more info on accessing variables via another variable.

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