I have been working on a function to manipulate arrays...
var myArray = [2, 1, 1, 1, 1];
and I want to transform it into this
[3, 1, 1, 1]
The function I created accepts 3 parameters
- ArrayToProcess - the array that will be processed
- indexTarget - the selected value defined by index
- morphToValue - the value I want the selected value to become
My main goal is to accept the indexTarget, for example
myFunction(myArray, 0, 3); //myArray is [2, 1, 1, 1, 1]
The objective is for the function to loop over the myArray
and add numbers in the array until it reaches the morphToValue
resulting in [3, 1, 1, 1]. It removes the 2
at the first index and 1
at the second index to add 3
. It also subtracts any excess number from the morphToValue
Another example would be to transform the array
var myArray = [2, 1, 1, 1, 1];
into this
[2, 1, 3];
by calling myFunction like this
myFunction(myArray, 2, 3);
How can I achieve this? I also want the function to restart iteration from the beginning of the array if the indexTarget is set to the last index of the array, resulting in
var myArray = [2, 1, 1, 1, 1];
it should become
[1, 1, 1, 3]; //when I invoke myFunction(myArray, 4, 3);
Please let me know in the comments if you need further clarification...
This is the code I have tried so far http://jsfiddle.net/eESNj/
var myArray = ['2', '1', '1', '1', '1'];
indexPurge(myArray, 0, 3);
function indexPurge(haystack, indexTarget, morphToValue) {
var toIntHaystack = [];
for (var i = 0; i < haystack.length; i++) {
toIntHaystack.push(parseInt(haystack[i]));
}
console.log(toIntHaystack); //before
var i = 0;
var purgedValue = 0;
do {
console.log(i + ' - ' + toIntHaystack[i]);
purgedValue += toIntHaystack[i];
toIntHaystack.splice(i, 1);
if (purgedValue >= morphToValue) {
break;
}
i++;
} while (i < toIntHaystack.length);
toIntHaystack.splice(indexTarget, 0, morphToValue); //after
console.log(toIntHaystack);
}