1

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 
2
  • 5
    How is 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 0 1 0 1 0 a 2d array? Commented Jul 22, 2018 at 19:07
  • It was lost in the formatting. (Hitting "edit" you could see what he meant but there's pending fix now so...) Commented Jul 22, 2018 at 19:09

6 Answers 6

3

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; }

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

1 Comment

... Array.from iterates over the characters of one of the strings, and then calls Number on each and returns the results as a new array, effectively turning "10010" into [1, 0, 0, 1, 0]
0

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);

Comments

0

this way, you will have 2d array of zero and ones

const newArr = strArr.map((a) => a.split("").map(char => char === "0"? 0: 1))

Comments

0

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);

Comments

0

Loop over each item and spread its content into an array - then convert to a number.

let newArr = strArr.map(item => [...item].map(Number));

Comments

0

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  ) );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.