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

javascript Extract multiple series array from string

I have string like

var t = 'red: 5, purple: 7, fuchsia: 10, green: 8';

I want to make array like

a = ['red', 'purple', 'fuchsia', 'green'];
b = [ 5, 7, 10, 8]

Please help me

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 :

Sample solution:

const t = 'red: 5, purple: 7, fuchsia: 10, green: 8';

const tarr = t.split(', ');

const a = [];
const b = [];

for (const item of tarr) {
  const [k, v] = item.split(': ');
  a.push(k);
  b.push(~~v); // '~~' is a shortcut to convert string value to number
}

console.log(a, b);
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