I am currently seeking a solution to divide an array of articles into subarrays based on the first key-value pair and its order.
After researching several Stack Overflow posts, I have come across one that seems to align closely with my objective:
break array of objects into separate arrays based on a property
Despite encountering many questions related to reduce functions, I am facing some difficulties. Specifically, I am struggling with:
What sets my problem apart: Rather than splitting the arrays into two distinct categories (such as "markup" and "video"), I aim to group all "markup" items together in the first array until a "video" item is encountered. Subsequently, I want to create an array containing all "video" items until the next "markup" item, followed by a new array of "markup" items until the subsequent "video" item, and so forth.
To demonstrate what I am attempting to achieve, here is a REPL example: REPL reproducing problem
The structure of the data is as follows:
export default [{
"type": "markup",
"element": "p",
"html": "blah"
}, {
"type": "markup",
"element": "p",
"html": "blah"
},
...
]
The desired outcome post JavaScript reduce operation:
[
[
{type: 'markup', element: 'p', html: 'blah' /*...*/ },
{type: 'markup', element: 'p', html: 'blah' /*...*/ },
...
],
[
{type: 'embeddedVideo', /*...*/ }
],
[
{type: 'markup', element: 'p', html: 'blah' /*...*/ },
{type: 'markup', element: 'p', html: 'blah' /*...*/ },
...
]
]
My current progress:
import articleBody from './articleBody.js';
function groupBy(arr, property) {
return arr.reduce((prop, x) => {
if (!prop[x[property]]) { prop[x[property]] = []; }
prop[x[property]].push(x);
return prop;
}, {});
}
let outputSample = groupBy(articleBody, "type");
console.log(outputSample)
The above code effectively generates two arrays differentiated by "markup" and "video"; however, it overlooks the original data's sequence and fails to produce distinct arrays based on the specified order.
If you could provide guidance or suggest an elegant resolution to this conundrum, it would be greatly appreciated. Thank you for your assistance.