Reputation: 99
How do I convert this array :
let strArr = ["10100", "10111", "11111", "01010"];
into a 2-d array.
The 2-d array will be :-
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
0 1 0 1 0
Upvotes: 1
Views: 132
Reputation: 98
let inArr = ["10100", "10111", "11111", "01010"];
let outArr = inArr.map( line => line.split("").map( item => +item ) );
console.log(outArr);
let inArr = ["10100", "10111", "11111", "01010"];
let outArr = inArr.map( line => line.split("").map( item => +item ) );
Upvotes: 0
Reputation: 3405
Loop over each item and spread its content into an array - then convert to a number.
let newArr = strArr.map(item => [...item].map(Number));
Upvotes: 0
Reputation: 15115
let strArr = ["10100", "10111", "11111", "01010"];
let numColumns = strArr[0].length;
let numRows = strArr.length;
let string = strArr.join('');
let result = [];
for (let row = 0; row < numRows; row++) {
result.push([]);
for (let column = 0; column < numColumns; column++) {
result[row].push(parseInt(string.charAt(row*5 + column), 10));
}
}
console.log(result);
Upvotes: 0
Reputation: 386620
You could get the iterables from string and map numbers.
var array = ["10100", "10111", "11111", "01010"],
matrix = array.map(s => Array.from(s, Number));
console.log(matrix);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 3
Reputation: 984
this way, you will have 2d array of zero and ones
const newArr = strArr.map((a) => a.split("").map(char => char === "0"? 0: 1))
Upvotes: 0
Reputation: 745
If the result needs to be an array of array containing one element per character of a string, you can split each string with an empty string in a loop or map.
let res = [];
let strArr = ["10100", "10111", "11111", "01010"];
strArr.map((str) => {
res.push(str.split(''))
});
console.log(res);
Upvotes: 0