I have an array like this
var arr = ['2021-07-09T00:00:00Z','9242.80','4316.91','32557.90','14687.00','2021-07-10T00:00:00Z','9242.80','4316.91','32557.90','14687.00','2021-07-11T00:00:00Z','9242.80','4316.91','32557.90','14687.00','2021-07-12T00:00:00Z','9242.80','4316.91','32557.90','14687.00']
I'd like to make 4 different arrays from this one array (either by the date or the order of the items (so after every 5 items it creates a new array. I haven't been able to work it out even after searching. Could someone please point me in the right direction?
You can use reduce here to achieve the desired result.
var arr = [
"2021-07-09T00:00:00Z",
"9242.80",
"4316.91",
"32557.90",
"14687.00",
"2021-07-10T00:00:00Z",
"9242.80",
"4316.91",
"32557.90",
"14687.00",
"2021-07-11T00:00:00Z",
"9242.80",
"4316.91",
"32557.90",
"14687.00",
"2021-07-12T00:00:00Z",
"9242.80",
"4316.91",
"32557.90",
"14687.00",
];
const result = arr.reduce((acc, curr, i) => {
if (i % 5 !== 0) acc[acc.length - 1].push(curr);
else acc.push([curr]);
return acc;
}, []);
console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can also generalize the function as:
var arr = [
"2021-07-09T00:00:00Z",
"9242.80",
"4316.91",
"32557.90",
"14687.00",
"2021-07-10T00:00:00Z",
"9242.80",
"4316.91",
"32557.90",
"14687.00",
"2021-07-11T00:00:00Z",
"9242.80",
"4316.91",
"32557.90",
"14687.00",
"2021-07-12T00:00:00Z",
"9242.80",
"4316.91",
"32557.90",
"14687.00",
];
function splitArrayAfter(arr, num) {
return (result = arr.reduce((acc, curr, i) => {
if (i % num !== 0) acc[acc.length - 1].push(curr);
else acc.push([curr]);
return acc;
}, []));
}
console.log(splitArrayAfter(arr, 5));
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using Array#reduce, you can iterate over the array. At every iteration, we add a new array if we're just starting (i.e. no sub-arrays), the element is a date, or we've reached 5 elements. Otherwise, add the element to the latest sub-array:
const arr = ['2021-07-09T00:00:00Z', '9242.80', '4316.91', '32557.90', '14687.00', '2021-07-10T00:00:00Z', '9242.80', '4316.91', '32557.90', '14687.00', '2021-07-11T00:00:00Z', '9242.80', '4316.91', '32557.90', '14687.00', '2021-07-12T00:00:00Z', '9242.80', '4316.91', '32557.90', '14687.00'];
const res = arr.reduce((list, e) => {
if(Date.parse(e) || list.length === 0 || list[list.length-1].length === 5) {
list.push([e]);
} else {
list[list.length-1].push(e);
}
return list;
}, []);
console.log(res);