logicMonster
logicMonster

Reputation: 17

how to iterate a string array and concat elements together in javascript?

getPath(array, 0) will return "A"
getPath(array, 1) will return "AB"
getPath(array, 2) will return "ABC"

function getPath(arr, idx){  
  // todo ...     
}  
var array = ["A","B","C"];  

Upvotes: 0

Views: 137

Answers (2)

faheem farhan
faheem farhan

Reputation: 411

Plain old for loop style:

 function getPath(arr, idx){
   var output="";  
    for(i=0;i<idx;i++){
    output= output + array[i]
    }
  return output;
}  
var array = ["A","B","C"]; 

Upvotes: 0

boehm_s
boehm_s

Reputation: 5544

function getPath(arr, idx){  
  return (arr.slice(0, idx+1).join(""));  
}  

Yes, you're right, thx Redu

Upvotes: 2

Related Questions