I'm trying to create a function in JavaScript that rearranges the indices of an array.
I came up with the following idea, but using this method I have to make a new else if clause for every possible length of the array given as fourth argument for the method reformatArray
.
Can parameters in a method be added in a more intuitive way?
Code:
function start() {
var array1 = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8"];
reformatArray(array1, 1, 2, [1, 2, 0]);
//output should be ["Item 1", "Item 3", "Item 4", "Item 2", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8"]
//WORKS
var array2 = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8"];
reformatArray(array2, 2, 5, [3, 1, 3, 2]);
//output should be ["Item 1", "Item 2", "Item 6", "Item 4", "Item 6", "Item 5", "Item 8"]
//DOES NOT WORK because array as fourth argument is greater than 3 in length
}
function reformatArray(array, startIndex, numOfIndicesToReplace, newIndicesPositions) {
var newPosLength = newIndicesPositions.length;
if (newPosLength == 0) {
array.splice(startIndex, numOfIndicesToReplace);
} else if (newPosLength == 1) {
array.splice(startIndex, numOfIndicesToReplace, array[startIndex + newIndicesPositions[0]]);
} else if (newPosLength == 2) {
array.splice(startIndex, numOfIndicesToReplace, array[startIndex + newIndicesPositions[0]], array[startIndex + newIndicesPositions[1]]);
} else if (newPosLength == 3) {
array.splice(startIndex, numOfIndicesToReplace, array[startIndex + newIndicesPositions[0]], array[startIndex + newIndicesPositions[1]], array[startIndex + newIndicesPositions[2]]);
}
//etc.
}
Thanks in advance.