Problem
I’ve written a function to sort an array that interweaves an arrays values in the way of if you had two separate arrays [1,2,3,4,5] on one side and [6,7,8,9,0] on the other and it becomes [1, 6, 2, 7, 3, 8, 4, 9, 5, 0].
The code works, but I’m wondering how it can be cleaned up and be more performant without the need for three additional arrays and to see if it can be done on the cards array itself.
let data = [1,2,3,4,5,6,7,8,9,0];
const interweave = data => {
const _data = [];
const l = data.slice(0, data.length / 2);
const r = data.slice(data.length / 2, data.length);
if (l.length === r.length) {
for (let i = 0; i < l.length; i++) {
_data.push(l[i], r[i]);
}
}
return _data;
}
interweave(data);
Solution
One approach would be to utilize .splice()
instead of .slice()
and .shift()
.
If the input array is expected to be mutated const copy = [...arr]
can be removed and the array methods can be called on input arr
: data
let data = [1,2,3,4,5,6,7,8,9,0];
const interweave = arr => {
const copy = [...arr]; // copy input
const r = copy.splice(Math.ceil(copy.length / 2)); // splice half of input
for (let i = 1; r.length; i += 2) // set `i` to `1` increment by `2`
copy.splice(i, 0, r.shift()); // use `.splice()` and `.shift()`
return copy; // return `copy`
}
console.log(interweave(data));