dimanche 30 novembre 2014

JavaScript: Re-order an array


I read a few answers on SO about the problems when dealing with splice (including Move an array element from one array position to another) but I was unable to solve my problem.


I am trying to reorder an array in a particular pattern. Let's assume the pattern is that all the negative numbers should be to the left of the array and all the postive numbers should be to the right of the array. The negative and positive numbers should be separated by zeros if any. It is important that the order be maintained



Sample Input = [3,0,2,-1,0,-3]
Desired Output = [-1,-3,0,0,3,2]


This is the code I wrote



function reorderArray(inputArray) {
origLength = inputArray.length
var indexZero = -1;
for (var i = 0; i < origLength; i++) {
if (inputArray[i] > 0) {
inputArray.push(inputArray[i]);
inputArray.splice(i, 1);
} else if (indexZero == -1 && inputArray[i] == 0) {
indexZero = i;
} else if (indexZero != -1 && inputArray[i] < 0) {
inputArray.splice(indexZero, 0, inputArray.splice(i, 1))
indexZero++;
}
}
alert(inputArray);
}


I run into a problem in the first step itself where I attempt to move all positive numbers at the back of the array because of the re-indexing. I can't start from the last index because that would mean losing the order and I can't use the i-- since it would run infinitely.


Any help with how I could make my code work would be appreciated. Additionally, if there is an alternative that is more efficient than splice, that would be welcome too.


Thanks.





Aucun commentaire:

Enregistrer un commentaire