function getIdentityMatrix(n) { let arr = []; if (n === 1){ return [[1]]; } if (n === 0){ return []; } return (new Array(n).fill(0)).map(function(item,i,arr) { item = (new Array(n).fill(0)).fill(1); return arr; }); } 

My function creates a matrix filled with zeros. Can not add units.

  • why don't you want a simple loop to use? - Grundy
  • besides, assigning a value to the item parameter inside the map is meaningless - Grundy
  • The meaning of the task is to do it without loops. - Vitalik Mileshko
  • And this is not you writing on Habré? After your past question, an article appeared with very similar examples. - user220409
  • No, I never wrote articles on Habré. - Vitalik Mileshko

1 answer 1

 function getIdentityMatrix(n) { return (new Array(n).fill(0)).map( function (a, i){ return (new Array(n)).fill(0).map(function (b,j){return (i==j)?1:0;}); } ) } var t=getIdentityMatrix(5); for(i=0; i<5; i++){console.log(t[i].join(" "))} 
  • Thanks for the decision - Vitalik Mileshko