Last active
January 12, 2023 09:38
-
-
Save miroswd/88b7f39b036ea23e238d4f6eb7ec69c5 to your computer and use it in GitHub Desktop.
Slice array items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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