What is the best way to obtain an overlapping offset and generate a subset from a string using JavaScript?

My task involves processing a text string and an array of blocks, each containing an object representing the offset from the beginning and end of the string. The goal is to create unique blocks by aggregating based on the largest offset. See below for a sample:

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 the example above, "the GitHub Actions “New Workflow” experience." is the largest word, which includes sub-words like "GitHub" and "GitHub Actions". Therefore, our final set will include the largest word with its start and end offsets, while the other two will be split apart.


Desired 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",
      },
    ],
  },
];

Answer №1

To implement grouping by hashing, you can follow this method:

const elements = [{name: "Apple", start: "15", end: "20"},{name: "Banana", start: "40", end: "48"},{name: "Apple Pie", start: "12", end: "26"},{name: "the Apple Pie recipe from scratch.", start: "8", end: "37"}];

const grouped = elements.reduce((accumulator, element) => {
    const [{ start, end }] = elements
      .filter((e) => (e.start <= element.start) && (e.end >= element.end))
      .sort((e1, e2) => (e2.end - e2.start) - (e1.end - e1.start));
      
    const hash = `${start}-${end}`;
    accumulator[hash] = accumulator[hash]
      ? { ...accumulator[hash], pieces: [...accumulator[hash].pieces, element] }
      : { start, end, pieces: [element] };
    
    return accumulator;
}, {});
const finalResult = Object.values(grouped);

console.log(finalResult)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Detecting collisions between multiple blocks on an HTML5 canvas

Recently, I've been working on developing a game that involves falling blocks which stack on top of each other. These blocks are programmed to fall into one of six columns and should halt their descent upon collision with the block at the top of that ...

Despite the headers being in place, the node is still the point of

I am facing an issue with two URLs residing on the same server, mydomain.com and api.mydomain.com In order to handle access-origin in my API, I have included the following code snippet: app.use(function (req, res, next) { // CORS headers res.head ...

Tips for merging an array with a timestamp column included

Within my PHP code, I am working with an array that looks like this: [ // 'Timestamp' => 'data', '1296001511 ' => '2', '1295994311' => '25', '1295965511' => '34&apo ...

POST request in Ajax with NodeJs/MongoDB/Mongoose causing an Uncaught TypeError: Illegal invocation

Whenever I attempt to make a POST request using Ajax/Jquery, I keep encountering an error in the console. The specific errors are on lines 67 and 31 in the createTeam.js file: $.ajax({ //line 67 sendInvitation(teamID,_companyName,teamName) //lin ...

Capture the height values from various divs and store them in an array, then utilize these values to adjust the size of other

My goal is to achieve the following: (1) Collect heights from multiple divs and store them in an array. (2) Apply these heights to other elements. The first element should receive the first value, the second element should receive the second value of the ...

What is the best method for embedding <ng-click> in a string within Endpoint.java and then returning this string to the client side?

I'm currently developing a messaging feature within a Chat application that facilitates communication between logged in users via the Web Socket protocol. In order to enhance user interaction, I am looking to incorporate a reply option into each messa ...

Utilizing jQuery UI Slider for Calculating Percentage

I recently worked on an example where I incorporated 5 sliders, which you can see here: Example: http://jsfiddle.net/redsunsoft/caPAb/2/ My Example: http://jsfiddle.net/9azJG/ var sliders = $("#sliders .slider"); var availableTotal = 100; ...

Converting a _bsontype objectID value to a string/objectID for insertion into MongoDB using node.js

I am facing an issue with a JSON file that contains objects as shown below. { userID: {"_bsontype":"ObjectID","id":{"0":92,"1":237,"2":216,"3":42,"4":254,"5":178,"6":68,"7":182,"8":208,"9":254,"10":51,"11":64}}, userName: "abc" } Note: The data a ...

Java program that reads data from a file, saves the string information into an array, and then modifies and writes this string data

I've been grappling with this question for hours, so any help would be greatly appreciated. My task is to read a file via command line argument that contains information about several students - their names, majors, IDs, and graduation dates. I then n ...

Secured interactions following authentication using React Query and NextAuth

After successfully signing in to my Nextjs app using NextAuth, I encountered an issue with sending authenticated requests to my API. The data returned after signing in appears to be for an unauthenticated user. I suspect that the problem lies in React Que ...

Can a function return another function?

As I delve into my Javascript learning journey, I encountered a puzzling Sa() function within this code snippet. Initially, I deemed it to be an unsolvable problem like the Kobayashi Maru, but upon closer inspection, I suspect that this Sa() function migh ...

Creating an element with a specified class name in javascript: A step-by-step guide

What is the process for creating an element with a specific class name using JavaScript? I attempted to create an element like the following: <div class ="dialog_red_top_page"> <div class ="inner_dialog_red_top_page"> <p class= ...

Is there a way to retrieve $httpProvider.defaults.xsrfCookieName within .factory?

Here's a question that might come from someone new to programming. I'm trying to avoid hard-coding the values for xsrfHeaderName and xsrfCookieName. Can anyone guide me on how to retrieve them from the $httpProvider? .factory('XSRFIntercept ...

Material UI - Array of Chips

I have been working on creating a ReactJS component that displays an array of chips with unique styling for each one. To achieve this, I created individual makeStyles classes for the chips. However, I encountered difficulties in dynamically changing the cl ...

Extracting the JQuery library from its source code

Is there a simple method for extracting only the necessary functions from the jQuery library? I have found that many of the functions within the library are not being utilized, so it would be beneficial to remove them. ...

The code is functioning properly on both Codepen and JSFiddle

I encountered an issue where my code for the header to display only when scrolling up worked perfectly in jsfiddle or codepen, but failed when I tried it in my own program. It was puzzling because I copied and pasted the same code into both platforms and i ...

What could be the reason for AngularJS encoding the URLs for my POST parameters?

Take a look at our service's REST client: self.headers = { Accept: 'application/json', 'Content-Type': 'application/json' }; self.loginClient = $resource(self.baseUrl + '/users/login', { ...

Tips on how to update the page and create a counter for a table view

I am working with an HTMLB Tableview where I need to regularly update its firstRowVisible property every 3 minutes with a dynamic value. For example, if it starts at zero, after 3 minutes it should be set to 21 and continue increasing by a certain interval ...

Vue-incredible swiper, a pair of components swipe using buttons adjacent to one another

I am currently using vue-awesome-swiper and encountering an issue. The swipers on my page have buttons (prev slide, next slide) for navigating through slides. However, when I include two swipers on the same page, the buttons of one swiper end up affecting ...