Siva Siva - 3 days ago 5
Javascript Question

Print the number of values as take from the Index value from array

Recently Attended the interview, Some one asked the question like below:

var array = [0,1,2,3,4,5];


Output :

temp:
temp1:1
temp22:22
temp333:333
temp4444:4444
temp55555:55555


I tried below code it is working fine but is there any best solution for this example :

array.forEach(function(item,index){
var text ="";
if(index >= 2){
for(var j =1; j <= index; j++){
text += index;
}
console.log("temp"+text + ":" + text);
}else{
console.log("temp"+index + ":" + index);
}
});


Thanks in advance!

Answer

You could iterate the array and iterate the count. Then display the new string.

var array = [0, 1, 2, 3, 4, 5];

array.forEach(function (a, i) {
    var s = '';
    while (i--) {
        s += a;
    }
    console.log ('temp' + s + ':' + s);
});

Comments