Group array elements

JavaScript, Array · Oct 22, 2020

Creates an array of elements, grouped based on their position in the original arrays.

  • Use Math.max(), Function.prototype.apply() to get the longest array in the arguments.
  • Create an array with that length as return value and use Array.from() with a mapping function to create an array of grouped elements.
  • If lengths of the argument arrays vary, undefined is used where no value could be found.
const zip = (...arrays) => {
  const maxLength = Math.max(...arrays.map(x => x.length));
  return Array.from({ length: maxLength }).map((_, i) => {
    return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);
  });
};

zip(['a', 'b'], [1, 2], [true, false]); // [['a', 1, true], ['b', 2, false]]
zip(['a'], [1, 2], [true, false]); // [['a', 1, true], [undefined, 2, false]]

More like this

  • Group array elements based on function

    Groups elements based on position in the original arrays and combines them using a function.

    JavaScript, Array · Nov 3, 2020

  • Ungroup array elements based on function

    Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.

    JavaScript, Array · Jan 23, 2022

  • Count grouped elements

    Groups the elements of an array based on the given function and returns the count of elements in each group.

    JavaScript, Array · Nov 3, 2020