Skip to content

Instantly share code, notes, and snippets.

@miroswd
Last active January 12, 2023 09:38
Show Gist options
  • Save miroswd/88b7f39b036ea23e238d4f6eb7ec69c5 to your computer and use it in GitHub Desktop.
Save miroswd/88b7f39b036ea23e238d4f6eb7ec69c5 to your computer and use it in GitHub Desktop.
Slice array items
const arr = [1,2,3,4];
const splitedArrItems = [];
const splitIdx = 2;
const indice = arr.length/splitIdx;
for (let i = 0; i < indice; i++) {
splitedArrItems.push(arr.splice(0, splitIdx));
}
const obj = {}; // {0: '[1,2]', 1: '[3,4]'}
splitedArrItems.forEach((e, i) => {
// insert code logic here
obj[i] = JSON.stringify(e);
});
// reverse process
const joinedObjItems = []; // [[1,2], [3,4]]
for (let itemObj in obj) {
joinedObjItems.push(JSON.parse(obj[itemObj]))
}
joinedObjItems.flat() // [1,2,3,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment