I have a text and a array of blocks which have object which represent offset from starting and end offset of string. i want to make unique block from this and aggregate based on largest offset. a sample is below.
let text =
"announcing improvements to the GitHub Actions “New Workflow” experience. Now, when you want to create";
let blocks = [
{
word: "GitHub",
start: "31",
end: "37",
},
{
word: "Now",
start: "73",
end: "76",
},
{
word: "GitHub Actions",
start: "31",
end: "45",
},
{
word: "the GitHub Actions “New Workflow” experience.",
start: "27",
end: "72",
},
];
in above example "the GitHub Actions “New Workflow” experience." is largest word which have "GitHub" and "GitHub Actions" as sub set so in out start end offset set will with largest one and other two will be part of split
Expected output
let finalSplit = [
{
start: "73",
end: "76",
splits: [
{
word: "Now",
start: "73",
end: "76",
},
],
},
{
start: "27",
end: "72",
splits: [
{
word: "GitHub Actions",
start: "31",
end: "45",
},
{
word: "the GitHub Actions “New Workflow” experience.",
start: "27",
end: "72",
},
{
word: "GitHub",
start: "31",
end: "37",
},
],
},
];
You can use grouping by hash approach:
const blocks = [{word: "GitHub", start: "31", end: "37"},{word: "Now", start: "73", end: "76"},{word: "GitHub Actions", start: "31", end: "45"},{word: "the GitHub Actions “New Workflow” experience.", start: "27", end: "72"}];
const reduced = blocks.reduce((acc, block) => {
const [{ start, end }] = blocks
.filter((s) => (s.start <= block.start) && (s.end >= block.end))
.sort((s1, s2) => (s2.end - s2.start) - (s1.end - s1.start));
const hash = `${start}-${end}`;
acc[hash] = acc[hash]
? { ...acc[hash], splits: [...acc[hash].splits, block] }
: { start, end, splits: [block] };
return acc;
}, {});
const result = Object.values(reduced);
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }