Consider this scenario: I require the capability to rearrange any one-dimensional array so that the new array begins with the center number (if the object count is odd) or the center two numbers (if the object count is even), and then progresses from low to high until all numbers in the original array are accounted for.
For instance, in the case of an odd number of objects:
Original Array: [1,2,3,5,8,13,20]
New Array: [5,3,8,2,13,1,20]
Or for an even number of objects:
Original Array: [1,2,3,4]
New Array: [2,3,1,4]
I attempted to achieve this using a for loop, which worked theoretically but could not be implemented as a computed property in Vue.js.
This was my unsuccessful attempt:
gameInfo: {
cards: [1, 2, 3, 6, 8, 13, 21, 40, 1000],
}
reorderOddCards() {
ATTEMPT 1
const cardCount = this.gameInfo.cards.length;
const middleNumber = (cardCount / 2).toFixed(0);
const newCardOrder = this.gameInfo.cards.map(addToArray);
function addToArray(value, index) {
if (index < middleNumber) {
const newIndex = (((middleNumber - index) * 2) - 1);
newCardOrder.splice(newIndex, 1, value);
} else if (index === middleNumber) {
newCardOrder.splice(index, 1, value);
} else {
const newIndex = ((middleNumber - index) * 2);
newCardOrder.splice(newIndex, 1, value);
}
}
return newCardOrder;
},
Another method involving a .sort function was considered, but implementation has proven challenging.
Potential Solution