How to separate specific ranges within an array of numbers?

Scenario

In a client application, there is a table where users can select specific rows. Each row is identified by an ID which needs to be included in the URL for editing purposes. The process of creating this string occurs every time a row is selected or deselected.

Objective

The aim is to prevent the URL's query string from exceeding its maximum length by condensing ranges of numbers into a comma-separated string and passing the shortest query string possible. [5, 7, 8, 9, 77, 288] would become "5:9,77,288"

Answer №1

This is the solution I have arrived at, and it perfectly meets my requirements.

I am always receptive to enhancements and recommendations for improvement.

var prevIter = null;
var nextInRange = 0;
var maxRange = null;
var lastIndex = selectedIDs.length - 1;

selectedIDs.forEach(function(item, index) {
    if(index === 0) {
        IDs = item;
    }
    else {
        if(item === nextInRange) {
            if(index === lastIndex) {
                IDs = IDs + ":" + item;
                maxRange = null;
            }
            else {
                maxRange = item;
            }
        }
        else {
            if(maxRange == null) {
                IDs = IDs + "," + item;
            }
            else {
                IDs = IDs + ":" + maxRange + "," + item;
                maxRange = null;
            }
        }
    }
    prevIter = item;
    nextInRange = prevIter + 1;
}

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

JavaScript's onclick function for clearing dropdown fields will only work once for each specific dropdown field

I have scoured all the related questions and answers on StackOverflow, but none seem to address my specific issue. Here is the HTML code I am using: <select name="search_month" onclick="javascript: $('#categories').val(null);" id="months"> ...

Which is better: specifying Node.js version with nvmrc or in package.json engines

Ensuring that other developers working on my JavaScript project use specific versions of node and npm is important to me. I recently added the following code snippet to my package.json file: "engineStrict" : true, "engines": { "node" : "10.10.0", ...

Customizing the label styles within MUI's Chip component

Incorporating React with MUI's library has been a seamless experience for me. One of the key MUI components I have integrated is the Chip Within this particular Chip, there lies the label attribute, offering the option to showcase a text f ...

In Firefox, the parent div's width is greater than the combined width of its children

In Firefox, I am encountering a peculiar problem. The issue arises when I have a div with a height defined in a fixed px value, and an img element nested within it. While this configuration works fine in Chrome, in Firefox, the parent div's width end ...

Clicking outside the div will cause the div to be hidden

Looking for some help with a jQuery issue. I have a pop-up that opens when a div is clicked, but I want it to close when clicking outside of the div instead of just on the close button. <a class="close-up" href="#" onclick="popup('popUpDiv')" ...

Tips for reformatting an array of integers into separate formats

Is there a way to separate the values in an array? For example, from: $a = array(10,1234,144,2,101,231,213); To a new formatted array like this: 10 => 1/0/10.txt 1234 => 1/2/3/4/1234.txt 144 => 1/4/4/144.txt 2 => 2/2.txt 101 => 1/ ...

What is the process of retrieving data from a JSON array using PHP?

$employeeArray = array(); while ($row = mysqli_fetch_array($result, MYSQL_NUM)) { foreach ($row as $key => $value) { if ($value === '') { $row[9] ='We follow-up with you'; } ...

Store the advertisement click into the database utilizing PHP, subsequently access the provided hyperlink

I am developing a custom WordPress widget that displays advertisements. I want to track clicks on these ads and store the data in a database. The database table for click tracking is already set up, and I have a function called f1_add_advert_click($advert ...

the div's width isn't getting larger

Check out my code snippet: <script> var change = function(){ alert("sam"); for(var i; i >=200; i++){ var z = String(i); var x= document.getElementById("div1"); x.style.width = z; } }; </script> < ...

What is the best way to send checkbox values to ActionResult in MVC5?

I am working on an MVC5 application and within my view, I have the following code snippet: <div class="form-group"> @Html.LabelFor(model => model.CategoryID, "Category", htmlAttributes: new { @class = "control-label col-md-3" }) <div c ...

Angular $http not triggering

I am just starting to learn about angular js. In the project I am currently working on, I have created a code snippet for authorization in a directive. However, when I try to call the validateUser function, the $http post call does not seem to be executing ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

How can you display a single error message using Reactive Forms?

In Angular 7, I have implemented a Reactive Form with an input field named email. This input field is configured with two validators as shown below: email: ['', [Validators.email, Validators.pattern('^[\\w._]+@company(.com|.go|.je ...

What is the best way to pick an option from a dropdown menu using angularjs?

Is there a way to select an item from a dropdown list in AngularJS without using ng-repeat with an object array? I can easily select an option when using ng-repeat, but how can this be achieved with a normal select list? <select class="form-control" ...

Add JSON data to a table using jQuery and AJAX

When I make an AJAX call to retrieve data, the success part of the code looks like this: $("table.table").append("<tr><td>ID: " + item.ID + "</td><td>Name: " + item.name +" Url:</td><td><a href='https://.......s ...

Javascript window.scroll function malfunctioning in some browsers while running in localhost

Check out this codepen link where everything is working, but unfortunately not locally: https://codepen.io/LoudDesignStudios/pen/RwxPJKY <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> < ...

Is it possible to utilize the same module.css file across multiple components in a React project?

As a newcomer to React, I have discovered the benefits of using module CSS to address naming conflicts. Now, as I prepare to refactor my app, I have encountered a scenario where two components are utilizing styles from the same file. I am curious to lear ...

"Master the art of curl login authentication with this step-by-step guide

Looking to authenticate using curl with PHP or another language For example, visit this site: When the curl site prompts for authentication as shown in the image below, how do I log in to retrieve data? https://i.sstatic.net/LGNgl.png ...

"Utilizing JavaScript to Disable a MenuItem in ASP .NET: A Step-by-Step

I have successfully designed a customized menu interface using ASP.NET. <asp:Menu ID="Name1" runat="server" OnMenuItemClick="DoSth_MenuItemClick" Visible="true"> <Items> <asp:MenuItem Text="Function description" Value="Val" ToolTip=" ...

Error: Unexpected TypeError occurred stating that 'map' cannot be read from undefined, although the map method is not being used in the code

I have recently developed an Ethereum application for conducting transactions using React and the ethers module. Below, you can see a snippet of my code, specifically focusing on the function sendTransactions: import {ethers} from 'ethers'; impor ...