Reputation: 63
I have an array with 25 items (Will increase), and I want to split it into chunks of 10 each. After the 1st chunk, I want to insert an image and a component after the 2nd chunk of 10. Sharing the code I have written so far.
const DESKTOP_SPLIT = 10;
handleSplit = () => {
const { listings } = this.props;
let finalArr = [[]];
let currentArr = 0;
const myArray = [...listings];
for (let i = 0; i < listings.length; i++) {
if (i % DESKTOP_SPLIT === 0) {
currentArr += 1;
if (!finalArr[currentArr]) {
finalArr[currentArr] = [];
}
}
finalArr[currentArr].push(i);
}
return finalArr;
};
Expected output:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[<SomeComponent />],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[Some image],
[21, 22, 23, 24, 25, ...]
]
In the code above the myArray variable contains the array I want to split. How do I go forward with this and insert an element/component dynamically after every 10th element in the array?
Upvotes: 0
Views: 147
Reputation: 6627
Not entirely sure I've understood, but you could probably use the Array.splice method to achieve what you're after. Here's some code that will insert the string 'SPLICE'
after every second element in the array:
const SPLICE_AFTER = 2;
const data = ['One', 'Two', 'Three', 'Four', 'Five'];
const result = [...data];
for (let i = result.length - (result.length % SPLICE_AFTER); i > 0; i -= SPLICE_AFTER) {
result.splice(i, 0, 'SPLICE');
}
// Produces: ["One", "Two", "SPLICE", "Three", "Four", "SPLICE", "Five"]
console.log(result);
Note that you have to do this from the back to the front since the array grows after each time you do an insert.
Edit: Thanks for clarifying with the comment - I had misunderstood the splitting part you were referring to. You can use the Array.slice method instead to achieve what you're after:
const CHUNK_SIZE = 2;
const data = ['One', 'Two', 'Three', 'Four', 'Five'];
// This will be a two-dimensional array
const result = [];
for (let i = 0; i < data.length; i += CHUNK_SIZE) {
const chunk = data.slice(i, i + CHUNK_SIZE);
chunk.push("SPLICE");
result.push(chunk);
}
// Produces: [
// ['One', 'Two', 'CHUNK'],
// ['Three', 'Four', 'CHUNK'],
// ['Five', 'CHUNK']
// ]
console.log(result);
Here it is running at CodeSandbox
Upvotes: 1