Split the array into several arrays based on a specific threshold

I have a graph depicting an array [2,8,12,5,3,...] where the x axis represents seconds. I am looking to divide this array into segments when the y values stay 0 for longer than 2 seconds. For example, in this scenario the array would be split into 3 parts: x = 0 to 8, x = 8 to 13, and x = 13 to 20 due to the prolonged presence of y = 0 from 8 to 13. Given that this array could potentially be extensive, I am wondering what the quickest approach would be to accomplish this using pure JavaScript (or with lodash/underscore if necessary). Currently, my method involves iterating through the array to identify the 2-second pause points. Is there a more efficient way to achieve this?

https://i.sstatic.net/zn16F.png

Answer №1

An alternative approach involves utilizing a recursive method that iterates through the data while evaluating the presence of the desired zero value to determine if the threshold condition is met or not. If not, it will proceed to remove the last interval and add the length to the array.

The outcome of this method is as follows:

  • when threshold = 3:

    [
        [ 2,  8],
        [12, 20]
    ]
    
  • if threshold = 6:

    [
        [ 1, 20]
    ]
    

var x = [1, 2, 4, 5, 6, 7, 10, 12, 15, 16, 19, 20],
    y = [2, 7, 13, 6, 9, 1, 0, 3, 0, 7, 10, 11],
    threshold = 3,
    isZeroIncluded = false;
    response = [];

x.forEach(function (val, index) {
    var previous = response[response.length - 1];

    if ((y[index] === 0) !== isZeroIncluded) {
        if (previous) {
            previous[1] = val;
        }
        return;
    }

    isZeroIncluded = !isZeroIncluded;

    if (previous && isZeroIncluded && val - previous[0] < threshold) {
        response.pop();
        if (response[response.length - 1]) {
            response[response.length - 1][1] = val;
        }
        return;
    }

    response.push([val]);
});

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

Answer №2

To efficiently navigate through the array, it is crucial to analyze its values, limiting the solution to O(n) complexity. A practical approach involves iterating over the array while tracking the number of zeros encountered up to a certain point.

The following function offers a quick implementation of this strategy. It includes a variable for storing the previous index as well. Though the previous index could be inferred from the split array, doing so with large arrays might prove inefficient.

function divideArray(array, threshold) {
  var zeros = 0,
      previousIdx = 0,
      dividedArrays = [];
  array.forEach(function(element, index) {
    if (element === 0) {
      zeros++;
      if (zeros == threshold && previousIdx != index - threshold + 1) {
        dividedArrays.push(array.slice(previousIdx, index - threshold + 1));
        previousIdx = index - threshold + 1;
      }
    } else if (zeros >= threshold) {
      dividedArrays.push(array.slice(previousIdx, index));
      previousIdx = index;
      zeros = 0;
    }
  });
  if (previousIdx != array.length - 1) {
    dividedArrays.push(array.slice(previousIdx));
  }
  return dividedArrays;
}

A demonstration of this function's functionality using test data can be found on JSFiddle: https://jsfiddle.net/UniqueUser/examplelink123/

This code may still have room for further enhancements.

If your objective is solely to obtain section indices rather than splitting the array into separate arrays with data, you can replace the three occurrences of array.slice(a, b) with [a, b-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

Using Gulp Filter in Conjunction with Source Maps

My initial query was similar to this one here, but it led me to delve deeper into research and explore a new approach. Essentially, I am attempting to consolidate all my .js and .coffee files within a single gulp.src() object and execute relevant tasks ba ...

Enhancing user experience with Ajax login forms that seamlessly integrate with browser password remember functionality

I recently implemented an ajax-based login form on my website, but it seems that browsers are not recognizing it as a login form and therefore not offering to remember passwords for easier login access. Once the submit button is clicked, the entered value ...

Implementing i18n in NextJS with a focus on maximizing SEO performance

My task was to implement internationalization (i18n) for our company website. Currently, we are using Netlify with @netlify/plugin-nextjs, and I encountered an issue when trying to submit a PR. An error popped up stating: Error: i18n support is not compati ...

Tips for transferring form data from a React frontend to the backend Node.js server

I have been attempting to send FormData from React JS to my backend (Express Node server) with the code snippet provided below. However, I am encountering an issue where req.body.myFormData in expressTest.js is showing up as empty. Despite trying various ...

Discover ways to retrieve an ajax response from a different domain by submitting specific data to the controller method while operating on an internet server

I am facing an issue where I am unable to retrieve array data from a Codeigniter controller using an Ajax request. The data is being posted to the controller to fetch related data from the database, and it works perfectly fine on my local server. However, ...

Problem with Handlebars: When compiling, TypeError occurs because inverse is not recognized as a function

I've hit a roadblock with an error that I just can't seem to solve. My goal is to dynamically compile a template extracted from a div on the page, provide it with content, and then display it in a designated area of my webpage. Here's the s ...

It appears that Apexcharts is not compatible with React/Next.js

Issue Encountering a crash in my Next.js/React/Node application whenever I utilize import Chart from "react-apexcharts" in any file. Upon attempting to access the app, an error message is displayed: Server Error ReferenceError: window is not ...

Ajax fails to provide a response

Hey there, I'm trying to save the response from an HTML page and store the content of that page. However, every time I try, I keep getting an error message. What am I doing incorrectly? <script type="text/jscript"> var page = ""; $.aj ...

Unable to pass multiple objects as props in Vue component causing issues

Seeking help on passing multiple props to a component using v-for: <my-component v-for="(item, index) in items"></my-component> The data structure 'items' consists of: items: { 1: { name: "Apple", color: "Red" }, 2: { name: "Ba ...

Creating Chaos in PrimeFaces Page Navigation with JavaScript

I have implemented third-party connection monitoring code called Online JS by Denis Radin and it seems to be causing unexpected interactions with the navigation elements on my webpage. I am seeking insight into possible reasons for this behavior in order t ...

Is there a way to send a Map object to a script file using EJS?

I am facing an issue with passing a Map object to my client-side code. I have successfully used EJS and JSON.stringify(...) in the past for arrays, but it doesn't seem to work for Maps. When I try to console.log(myMap.keys()), I receive the following ...

Designing a login system with MEAN stack architecture?

I am currently in the process of building a web application using the MEAN stack (MongoDB, Express, AngularJS, and node.js). Specifically, I am working on implementing a login system and securing certain routes in my Angular app so that they are only acces ...

Disable toolbar focus in TinyMCE

Is there a method to prevent the appearance of the white square known as "Focus to toolbar" in TinyMCE? Clarification: Upon pressing Alt+F10 in TinyMCE, a white square is outlined around a button on the toolbar. This allows navigation among toolbar butto ...

What is the best way to create a list using only distinct elements from an array?

If I have a collection of different colors: Red Blue Blue Green I aim to extract only the unique colors and store them in an array. Subsequently, I plan to incorporate each color from that array into an existing color list. The desired outcome would l ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

Looking for a way to choose a button with a specific class name and a distinct "name" attribute using jquery?

I am currently working on developing a comment system. As part of this system, I want to include a toggle replies button when a user posts a reply to a comment. However, I only want this button to be displayed if there are no existing replies to the commen ...

The spread operator in Vuex is causing compilation errors with babel, as it continuously results in a module build failure

Currently, I am utilizing a spread operator within my mapGetters object. It is crucial to use a specific babel-preset-stage for proper ES6 compilation. Even after installing babel-preset-stage-2 via npm, I encountered the following error: ERROR in ./~/bab ...

Issue with importing a library into a Next.js component

I seem to be facing an unusual issue with my Nav component. Although I am able to import various items in my other components without any problems, for some reason, I cannot import anything into my Nav component. import { useState, useEffect } from "r ...

Transforming a unirest 'GET' call into an axios request

I am currently utilizing TheRundown API to access sports data. The example provided to me makes use of unirest, but I am endeavoring to adapt that example into an axios request. While I have managed to make it work for the most part, my main challenge lies ...

Difficulty redirecting Ajax call to a timed-out, CAS-protected server

Our website's login system utilizes CAS for single sign-on. The CAS server is operating the JASIG CAS server at , while our web server runs on Rails at . Due to security reasons, the Rails server has a relatively short session timeout, resulting in o ...