Reputation: 306
I am trying to divide the javascript array in chunks of a minimum of 5 using the below function. the x and z should have only 5 or less than 5 only. and I am also trying it with date condition. I have tried it with the below function for the inner x and z but it didn't worked so looking for some help with proper function.
sample input
"data": [
{
"date": "01-18-2022",
"x": [
60,
59,
58,
57,
56,
55,
54,
53,
52,
51,
50,
49,
48,
47,
46
],
"z": [
61,
60,
59,
58,
57,
56,
55,
54,
53,
52,
51,
50,
49,
48,
47
]
}
],
expected output
"data": [
{
"date": "01-18-2022",
“x: [
60,
59,
58,
57,
56,
],
“Z”: [
61,
60,
59,
58,
]
},
{
"date": "01-18-2022",
“x: [
55,
54,
53,
52,
51,
],
“Z”: [
55,
54,
53,
52,
51,
]
}, {
"date": "01-18-2022",
“x: [
50,
49,
48,
47
],
“Z”: [
50,
49,
48,
47
]
}
]
I used this function for the inside array, but it is not working.
function* generateChunks(array, size) {
let start = 0;
while (start < array.length) {
yield array.slice(start, start + size);
start += size;
}
}
Upvotes: 1
Views: 59
Reputation: 691
perhaps this helps:
dataJSON = {
"date": "01-18-2022",
"x": [
60,
59,
58,
57,
56,
55,
54,
53,
52,
51,
50,
49,
48,
47,
46
],
"z": [
61,
60,
59,
58,
57,
56,
55,
54,
53,
52,
51,
50,
49,
48,
47
]
}
function* chunkData(dataJSON, chunkSize){
let keys = Object.keys(dataJSON);
keys = keys.filter(x => x !== "date");
let maxSize = Math.max(keys.reduce(key => dataJSON[key].length));
start = 0;
while(start < maxSize){
let chunk = {
"date": dataJSON["date"]
};
for(let key of keys){
chunk[key] = dataJSON[key].slice(
start,
Math.min(
start + chunkSize,
dataJSON[key].length
)
);
}
start += chunkSize;
yield chunk;
}
}
for(let x of chunkData(dataJSON, 5)){
console.log(x);
}
Upvotes: 0
Reputation: 1265
try this:
let data = [
{
"date": "01-18-2022",
"x": [
60,
59,
58,
57,
56,
55,
54,
53,
52,
51,
50,
49,
48,
47,
46
],
"z": [
61,
60,
59,
58,
57,
56,
55,
54,
53,
52,
51,
50,
49,
48,
47
]
}
];
function arrayChunk(dataItem, chunkSize){
let res = []
for (let i = 0; i < dataItem.x.length; i += chunkSize){
res.push({
date: dataItem.date,
x: dataItem.x.slice(i, i + chunkSize),
z: dataItem.z.slice(i, i + chunkSize),
})
}
return res
}
data = data.map(dataItem => arrayChunk(dataItem, 5)).flat();
console.log(data);
Upvotes: 1