0
\$\begingroup\$

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);

\$\endgroup\$
  • \$\begingroup\$ I wouldn't call this deck shuffled. It all depends on your definition of shuffling. \$\endgroup\$ – vnp Jan 30 at 4:01
  • \$\begingroup\$ @vnp, updated the wording \$\endgroup\$ – totalnoob Jan 30 at 4:09
1
\$\begingroup\$

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));

\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.