-2

I try to add string string element to array using map as follows, but the code do not work. What's wrong there?

function towerBuilder(nFloors) {
 let towerArray = [];
 towerArray.length = nFloors; 
 let arrItem = '*' + ' ';
 let newArr = towerArray.map(function(item, i) {
   let n = 2 * i + 1;
   item = arrItem.repeat(n);
   return item;
 });
}
Evgeny Ladyzhenskiy
  • 151
  • 1
  • 3
  • 15
  • 2
    Have you tried debugging using the debugging tools, rather than the rather slow method of debugging through a website? – Phylogenesis Oct 12 '16 at 08:32
  • I'm testing it here - https://jsfiddle.net/44g3gLkd/ - an getting array of undefined elements. – Evgeny Ladyzhenskiy Oct 12 '16 at 08:38
  • 1
    Every web browser has debugging tools that allow you to set breakpoints and step through the code to find out what is happening. It is worth learning how to use them properly. – Phylogenesis Oct 12 '16 at 08:39

2 Answers2

2

Array.map will skip undefined values. So you will have to use new Array(length).fill(dummyValues)

function towerBuilder(nFloors) {
  let towerArray = new Array(nFloors).fill("")
  let arrItem = '*' + ' ';
  let newArr = towerArray.map(function(item, i) {
    let n = 2 * i + 1;
    item = arrItem.repeat(n);
    return item;
  });
  console.log(newArr)
}
towerBuilder(3)

Reference

Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
0

You can try the following code to solve your issue:

function towerBuilder(nFloors) {
  var stars = '*';
  var count;
  var array=[];
 for (var i = 0; i<=nFloors-1; i++){
  count = stars.repeat(2 * i + 1);
  array.push(count);
}

return array;
}
Fabien
  • 4,862
  • 2
  • 19
  • 33
Mohamed Fathy
  • 126
  • 1
  • 8