Last active
June 20, 2018 10:21
-
-
Save elitenomad/15423061bc25da81c1c3e5de6727fd72 to your computer and use it in GitHub Desktop.
Join elements of an array given a delimiter (Recursive and Regular loop methods)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const joinElements = (array, joiner) => { | |
const recurse = (index, resultSoFor = '') => { | |
resultSoFor += array[index]; | |
if (index == array.length - 1) { | |
return resultSoFor; | |
} else { | |
resultSoFor = resultSoFor + joiner; | |
return recurse(index + 1, resultSoFor); | |
} | |
}; | |
return recurse(0, ''); | |
}; | |
const joinElementsRegularLoop = (array, joiner) => { | |
let resultSoFor = ''; | |
array.forEach((element, index) => { | |
resultSoFor += array[index]; | |
if (index != array.length - 1) { | |
resultSoFor = resultSoFor + joiner; | |
} | |
}); | |
return resultSoFor; | |
}; | |
const result = joinElements(['s', 'cr', 't', 'cod', ' :):)'], 'e'); | |
console.log(result); | |
const resultForRegularLoop = joinElementsRegularLoop( | |
['s', 'cr', 't', 'cod', ' :):)'], | |
'e' | |
); | |
console.log(resultForRegularLoop); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment