JavaScript function to divide arrays into sequences

I have an array that looks like this:

var arr = [12, 13, 14, 17, 18, 19, 20]

I'm trying to figure out how to iterate through this array and split it into two arrays based on sequences. Essentially, if i+1 != true, I want to create a new array.

var arr = [12, 13, 14]
var arr2 = [17, 18, 19, 20]

I've been using lodash and experimenting with different for loops and splice methods, but I'm starting to feel a bit confused. Any assistance would be greatly appreciated.

Answer №1

Check out this example on jsFiddle

var numbers = [1, 2, 3, 5, 6, 7];

var result = [];
var temp = [];

for (var index = 0; index < numbers.length; ++index)
{
    if (index == 0)
    {
        temp.push(numbers[index]);
        continue;
    }
    if (numbers[index - 1] != (numbers[index] - 1))
    {
        result.push(temp);

        temp = [];
    }

    temp.push(numbers[index]);
}
result.push(temp);

result will store all the arrays

Find the Minified version here

function separateSequences(arr, res, temp, i){temp=[];res=[];for(i=0;i<arr.length;++i){if(!i){temp.push(arr[i]);continue}if(arr[i-1]!=arr[i]-1){res.push(temp);temp=[]}temp.push(arr[i])}res.push(temp);return res}

var finalResult = separateSequences([1, 2, 3, 5, 6, 7]);

Answer №2

Here is an alternative, more compact method that leverages underscore's handy groupBy and values functions:

var origin = [12,13,14,15,17,18,19,21,22,23];
var c = 0, result = _.values(_.groupBy(origin, function(el, i, arr) { 
  return i ? c += (1 !== el - arr[i-1]) : 0; }) );

After running this code, the result array will contain all the sequences as elements. You can experiment with it on this JSFiddle.

Explanation: The groupBy function groups the input array using a callback that assigns a new sequence number each time the difference between the current element (el) and the previous one (arr[i-1]) is greater than 1. Since it returns an object, _.values is used to convert it into an array; this step may be optional.

I am curious if it would be possible to have a groupByInArray function. Although it should be simple to implement, it could prove very useful in scenarios like this.

Answer №3

Is this what you had in mind here?

function separate(array) {
    var result = [];
    var subResult = [];
    for (var j = 0; j < array.length; j++) {
        var len = subResult.length;
        if (len === 0 || subResult[len - 1] === array[j] - 1) {
            subResult.push(array[j]);
        } else {
            result.push(subResult);
            subResult = [array[j]];
        }
    }
    result.push(subResult);
    return result;
}

Answer №4

Give this a shot :)

let numbers = [1,2,3,4,6,7,8]; //example
let index;
let previousNum = numbers[0];
for (index = 1; index < numbers.length; index++) {
  if (previousNum + 1 === numbers[index]) {
    previousNum = numbers[index]; //++
  } else {
    break;
  }
}
let firstHalf = numbers.slice(0, index + 1);
let secondHalf = numbers.slice(index + 1);

http://jsfiddle.net/zajnH/

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

Unresolved Issue: Jquery Modal Fails to Activate on Subsequent Click for Ajax-

When I make an Ajax call, I load HTML into a div. This HTML content contains a jQuery modal that opens when clicked. However, on the first click, the modal opens correctly. On subsequent clicks, I receive the following error in the console: Uncaught Type ...

The link tag cannot be used inside a division element

I am facing an issue with a button that has three different states represented by images. While the button looks great and functions well, it fails to perform its primary function - linking to another document. Upon clicking the button, no action is initi ...

The targetFrame is not displaying the page

I am encountering an issue with my page design that involves frames. On the left frame, there is a menu, and when I click on it, it is supposed to load into another frame. However, instead of loading into the specified frame, it is loading into the same fr ...

Storing JSON location data in JavaScript

When converting JSON data into a list structure, I aim to use the "AAA.BBB[0].CCC.DDD[5].EEE" format as the ID. This way, any modifications made by a user to the content of that specific list item will directly affect the JSON data linked to that location. ...

What is the best way to display the key within an object in a mui-datatable?

I attempted to define it in the following manner: { name: "colorList", label: "Color", options: { filter: true, sort: true, customBodyRender: (value, tableMeta, updateValue) => { ...

Trouble with React Native Maps: Region not refreshing, causing map to remain stuck on a single location

My <MapView> is not updating the region properly when I scroll the map. It seems to be stuck on one region and doesn't update as expected. Even when I scroll, the same region is passed to this.props.onRegionChange, preventing the map from actual ...

Tips on identifying the method to import a module

Currently, I am including modules into my Node project like this: import * as name from "moduleName"; Instead of the old way: var name = require("moduleName"); In the past, we used require in Node projects. My question is, is there a difference in ...

What causes the variation in size between the next/image and img HTML elements?

Two Images, Different Sizes! https://i.sstatic.net/vpoNG.jpg There seems to be a discrepancy in size between the image rendered by the next/img component and the one displayed using the img element. Interestingly, they both use the same image source and ar ...

Leveraging a Mongoose Schema Method within a Exported Mongoose Model

Lately, I've been developing an authentication system that is designed to either create a new user if no user with a specific ID exists OR retrieve a user with an existing ID. Through my exploration, I discovered that it's possible to determine w ...

The Express.js server seems to be having trouble rendering a static JavaScript file

Currently, I am in the process of constructing a website and have implemented an express.js server to collect data submitted through a form. Prior to configuring the server, I had already developed the site using static js and css files. Once the connectio ...

When I try to upload an image onto my website, the layout of my text gets disrupted

There seems to be quite a gap between the welcoming message and the main body text. Significant spacing noticed between Title and body ...

The deployment on heroku encountered an error during the build process

I'm attempting to deploy my React application on Heroku, but I keep encountering the following errors: -----> Installing dependencies Installing node modules npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ...

A method for highlighting duplicate rows in a DataTable by formatting them with the same color

I am currently utilizing the DataTable plugin to display rows in a table. I would like to highlight duplicate rows in the same color scheme. Can someone please assist me with this issue? In the example below, the entry for Black Winters is duplicated. I ai ...

How can I send an item to a dialog in a different VueJS component?

Having multiple smaller components instead of one big component is the goal for my project. Currently, I have a component with a <v-data-table> that displays various items. Each row includes a button that, when clicked, opens a <v-dialog> showi ...

When using Sequelize, I encountered an error message from SQLite stating that the table does not exist despite having created

I am struggling to grasp the concept of how Sequelize operates and I can't figure out why I am encountering the SQLITE_ERROR: no such table: Users error even though I have created the table using sequelize.define. Here is my code: const { Sequelize, D ...

The system considers the resource as a script, yet it was transmitted with the MIME type of text

I am encountering an issue when trying to integrate AngularJS/JavaScript into my HTML document. Each time I try to load my index.html file, the following error message appears: Resource interpreted as Script but transferred with MIME type text/html: "http ...

When using firebase.firestore(), the data displayed is completely different and does not match the content of my actual database documents

I am trying to fetch data from firebase firestore using the following code: let db = firebase.firestore(); let locations = db.collection("location"); console.log("locations", locations); However, the logged data is coming back strange and not showing the ...

Obtain the CSRF token from a webpage using JavaScript

I am currently working on a project where I need to retrieve the csrf token from a web page built with Django using javascript. The structure of my HTML template is as follows: <div class = "debugging"> <p id = "csrf">{% csrf_token %}</p ...

I am unable to tap on the input field

Having a major issue here... I've encountered a problem with this website: sk.maze-it.dk When attempting to click on "BOOK MØDE" in the navigation bar and select an available date (e.g. 30) followed by clicking on "Book møde", two fields appear - o ...

iOS 10's autofocus feature experiencing difficulties in focusing on input

While using an application on my desktop or Android device, I have noticed that the input focus works perfectly fine. However, when I try to run the same application on iOS 10 Safari, the input focus does not seem to be working. It is worth noting that I ...