I don't understand why everybody comes up with overcomplex (and sometimes non functional) code. It's simple task! No callbacks, regexps are needed and they don't even make the code easy to understand!
Using Array.splice
and working with original array
/** Requires array of numbers, changes THAT array, returns null
* @param numbers array of numbers
**/
function addHyphenWhenEven(numbers) {
for(var i=1, l=numbers.length;i<l; i++) {
if((numbers[i]%2 + numbers[i-1]%2) == 0) {
//Splice inserts 3rd parameter before i-th position
numbers.splice(i, 0, "-");
//Must shift the positions as the array dimensions have changed
i--;l++;
}
}
}
Using new array
/** Requires array of numbers, returns new array with hyphens
* @param numbers array of numbers
* @return array with numbers and hyphens
**/
function addHyphenWhenEven2(numbers) {
if(numbers.length==0)
return [];
var result = [numbers[0]];
for(var i=1, l=numbers.length;i<l; i++) {
if((numbers[i]%2 + numbers[i-1]%2) == 0) {
result.push("-");
}
result.push(numbers[i]);
}
return result;
}
/** Requires array of numbers, changes THAT array, returns null
* @param numbers array of numbers
**/
function addHyphenWhenEven(numbers) {
for(var i=1, l=numbers.length;i<l; i++) {
if((numbers[i]%2 + numbers[i-1]%2) == 0) {
//Splice inserts 3rd parameter before i-th position
numbers.splice(i, 0, "-");
//Must shift the positions as the array dimensions have changed
i--;l++;
}
}
}
/** Requires array of numbers, returns new array with hyphens
* @param numbers array of numbers
* @return array with numbers and hyphens
**/
function addHyphenWhenEven2(numbers) {
if(numbers.length==0)
return [];
var result = [numbers[0]];
for(var i=1, l=numbers.length;i<l; i++) {
if((numbers[i]%2 + numbers[i-1]%2) == 0) {
result.push("-");
}
result.push(numbers[i]);
}
return result;
}
var random = [];
while(random.length<20)
{
random.push(Math.floor(Math.random()*10));
}
$("#res2")[0].innerHTML = addHyphenWhenEven2(random).join("");
addHyphenWhenEven(random);
$("#res1")[0].innerHTML = random.join("");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h2>Using <tt>Array.splice</tt></h2>
<div id="res1"></div>
<h2>Using second array that is returned:</h2>
<div id="res2"></div>