Skip to content

Instantly share code, notes, and snippets.

@nash403
Created June 29, 2016 12:48
Show Gist options
  • Save nash403/9c225cfe6d5fb665e9d26d19a6acf609 to your computer and use it in GitHub Desktop.
Save nash403/9c225cfe6d5fb665e9d26d19a6acf609 to your computer and use it in GitHub Desktop.
JS function that inserts a value between each elements of an array
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