Skip to content

Instantly share code, notes, and snippets.

@SanariSan
Created April 10, 2025 09:02
Show Gist options
  • Save SanariSan/4613e663d9ac9e0ff4a7d0467e7cca2b to your computer and use it in GitHub Desktop.
Save SanariSan/4613e663d9ac9e0ff4a7d0467e7cca2b to your computer and use it in GitHub Desktop.
Flat array to entries (pairs of key-val)
const arr = [1, 2, 3, 4, 5, 6]; // -> [[1,2],[3,4],[5,6]]
arr.reduce((acc, cur, i) => {
const pos = ~~(i / 2);
acc[pos] = acc[pos] ?? [];
if (i % 2 === 0) acc[pos].push(cur);
else acc[pos].unshift(cur);
return acc;
}, []);
arr.reduce(
(acc, cur, i, pos) => (
(pos = ~~(i / 2)), (acc[pos] = acc[pos] ?? []), (acc[pos][i % 2] = cur), acc
),
[],
);
arr.reduce((acc, cur, i) => {
if (i % 2 === 0) acc.push([cur]);
else acc.at(-1).push(cur);
return acc;
}, []);
arr.reduce(
(acc, cur, i) => (i % 2 === 0 ? acc.push([cur]) : acc.at(-1).push(cur), acc),
[],
);
Array.from({ length: Math.ceil(arr.length / 2) }, (_, i) =>
arr.slice(i * 2, i * 2 + 2),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment