Created
June 29, 2016 12:48
-
-
Save nash403/9c225cfe6d5fb665e9d26d19a6acf609 to your computer and use it in GitHub Desktop.
JS function that inserts a value between each elements of an array
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
function insertBetweenElements(arr, value) { | |
// Get first element in array | |
var first = arr.shift(); | |
// if array is empty return array | |
if (!first) return arr; | |
// insert the value | |
return arr.reduce(function(valeurPrecedente, valeurCourante, index, array){ | |
return valeurPrecedente.concat(value,valeurCourante); | |
},(Array.isArray(first) ? first : [first])); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment