1

i want to convert an array of strings to array of boolean using javascript.

i have an array of strings like below

const data = ["true", "false", "false", "false", "true"]

how can i convert above array of strings to array of booleans like below,

const data = [true, false, false, false, true]

how can i do this using javascript. could someone help me with this? thanks.

stackuser
  • 257
  • 1
  • 5
  • 14
  • 1
    Does this answer your question? [How can I convert a string to boolean in JavaScript?](https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript) – B001ᛦ Nov 10 '21 at 21:06

3 Answers3

4

You could map the parsed values.

const
    data = ["true", "false", "false", "false", "true"],
    result = data.map(j => JSON.parse(j));
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • If it's gonna be a boolean value always, might be faster (as in, run faster) to go the simple route of `data.map(j => j==='true')` - and for the record, I DO NOT KNOW if that is actually faster, as i'm not sure about the inner workings of JSON.parse – Count Spatula Nov 10 '21 at 21:08
4

if you want to save the result into a new variable use map

const data = ["true", "false", "false", "false", "true"]
const result = data.map(e => e === 'true')

if you want change the original variable (the variable named "data") use forEach:

data.forEach((e, i) => { data[i] = e === "true" })
Reza Mirzapour
  • 390
  • 3
  • 11
  • thanks i have tried it. but gives error this condition will always return false since the types boolean and string have no overlap at line data.map(e => e==='true') – stackuser Nov 10 '21 at 21:16
  • `data.map(e => e==='true')` => if element equals "true", turn it to `true` and othrewise turn it to `false` – Reza Mirzapour Nov 10 '21 at 21:22
1

Assuming you want to change the existing array instead of generate a new one... Just check to see if each one is "true."

You could use JSON.parse as well, but that's probably overkill if you just have true and false, and it might throw an error if there's anything else in the array.

const data = ["true", "false", "false", "false", "true"];

for(var i=0; i<data.length; i++) data[i] = data[i] === 'true';

console.log(data);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116