# How can I convert an Array boolean to an Array int

3

I have the following arrangements:

``````Array = [false, true, false, true];
``````

But I want to convert it to

``````Array2 = [0, 1, 0, 1];
``````

asked by sebamim 10.06.2018 в 18:43
source

1

``````const arreglo1 = [true,false,true]
const arreglo2 = []

arreglo1.forEach(function(index, value){
if(index === true){
arreglo2.push(1)
}else{
arreglo2.push(0)
}
})

console.log(arreglo2)``````

Check how it is that I declare an arrangement with the values in the format of   number and then an empty arrangement that will be filled with the   equivalent of those values but in Boolean format

UPDATE

I leave you the same exercise but done with the map method

``````const arreglo1 = [true,false,true]
const arreglo2 = []

arreglo1.map((index) => {
if(index === true){
arreglo2.push(1)
}else{
arreglo2.push(0)
}
})

console.log(arreglo2)``````

source
2

I propose this solution:

``````let array1 = [false, true, false, true]
let array2 = array1.map(e => Number(e)) // [0, 1, 0, 1]
``````

What I am doing is that each element of `array1` I apply the function `Number()` . This function converts the value entered to a number that represents that value. In this case `True` would be `1` and `false` would be `0` .

1
``````Array.map((e) => {

if (e) {
return 1;
}

return 0;

});
``````

Note that map returns a new array, so to use it, you must use it as an expression, or save it in a new variable. That is:

``````const Array2 = Array.map((e) => {

if (e) {
return 1;
}

return 0;

});
``````

1

Use the `map` method that all the arrays have from ES5. You do not need to create a new array or be doing push.

``````var Array2 = [false, true, false, true].map(function (item) {
return item ? 1 : 0
})

console.log(Array2) // [0, 1, 0, 1]
``````

Or with ES6 it is even more readable:

``````var Array2 = [false, true, false, true].map(item => item ? 1 : 0)

console.log(Array2) // [0, 1, 0, 1]
``````

What I can think of is: with your `Array1` , then you make a for loop with its values. Within that loop you do an if in which if `Array1=false` , make `push()` to `Array2` with value 0 and vice versa with `true` .