Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fill an array with arrays programmatically

Tags:

javascript

Here is a code to create an array of arrays named sims through a for loop and using str1.

so far I need to define the sims length manually, equal to length of str1 like : let sims = [[],[],[],[]]; (four arrays equal to four words on str1)

how can I fill sims with arrays programmatically?

var str1 = "do you ever looked";
var str2 = "do you fr ever looked";

let sims = [[],[],[],[]]; // instead I want let sims = []; 

let s1 = str1.split(" ")
let s2 = str2.split(" ")

for (var j = 0; j < s1.length; j++) {
  for (var i = 0; i < s2.length; i++) {
    sims[j].push(s1[j].toString());
  }
}

console.log(sims);
like image 362
Sara Ree Avatar asked Aug 06 '19 11:08

Sara Ree


1 Answers

You could just split, map and fill an array to accomplish the same output, no need for any for loop at that time

var str1 = "do you ever looked";
var str2 = "do you fr ever looked";

let subArrayLength = str2.split(" ").length;
let sims = str1.split(' ').map( value => new Array( subArrayLength ).fill( value ) );
console.log(sims);
like image 105
Icepickle Avatar answered Oct 18 '22 21:10

Icepickle