3

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.

1

3 Answers 3

4

You could map the parsed values.

const
    data = ["true", "false", "false", "false", "true"],
    result = data.map(j => JSON.parse(j));
    
console.log(result);

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

1 Comment

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
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" })

2 Comments

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')
data.map(e => e==='true') => if element equals "true", turn it to true and othrewise turn it to false
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.