Organize array elements based on their values - using javascript

I am currently exploring the most effective approach to divide an array into multiple arrays based on specific operations performed on the values within the array.

Imagine I have an array like this:

var arr = [100, 200, 300, 500, 600, 700, 1000, 1100, 1200]

I aim to separate this array into different arrays whenever the difference between elements exceeds 100.

The desired output would be:

var result = [[100, 200, 300], [500, 600, 700], [1000, 1100, 1200]]

What is the most efficient method to achieve this?

I have attempted using a traditional for loop with if conditions that check the difference between consecutive elements. Whenever the difference surpasses 100, a new array is created. However, I sense there could be a more optimized solution.

EDIT:-

This is the code snippet I have implemented. Although it is close, it is not yet complete. I did not invest further time as I was aiming to find a simpler version utilizing reduce or underscore -

var result = [], temp = [], difference;
for (var i = 0; i < array.length; i += 1) {
 if (difference !== (array[i + 1] - array[i])) {
    if (difference !== undefined) {
        result.push(temp);
        temp = [];
    }
    difference = array[i + 1] - array[i];
}
temp.push(array[i]);
}

if (temp.length) {
  result.push(temp);
}

Answer №1

To achieve this, one can utilize the reduce method.

var numbers = [100, 200, 300, 500, 600, 700, 1000, 1100, 1200];

var groups = numbers.reduce(function (accumulator, currentValue) {
  if (accumulator.length === 0) { // First Iteration
    accumulator.push([currentValue]);
    return accumulator;
  }

  var lastGroupIndex = accumulator.length - 1;
  var lastGroup = accumulator[lastGroupIndex];

  var lastElementIndex = lastGroup.length - 1;
  var lastElement = lastGroup[lastElementIndex];

  if (currentValue - lastElement <= 100) { // Add to current group
    lastGroup.push(currentValue);
    return accumulator;
  }

  accumulator.push([currentValue]); // Create new group
  return accumulator;
}, [])

Note: This approach avoids using ES6 features as it is based on the assumption that the codebase does not currently support ES6, particularly noted through the use of var.

Answer №2

This question really piqued my interest.

Update: Upon taking another look, it's not explicitly stated whether the input array is sorted or not. If it happens to be sorted, then utilizing the reduce function would make things much simpler.

Initially, I pondered if there might be a more efficient solution than O(nlogn). However, even with item grouping, the ultimate combined array remains completely sorted. Thus, if there exists a way to solve your problem faster than nlogn, you could also improve sorting time beyond nlogn.

Considering this, the most direct approach involves sorting the array and then partitioning it based on the last element encountered during iteration. Reduce proves to be an ideal tool in this scenario:

const input = [100, 200, 300, 500, 600, 700, 1000, 1100, 1200];

const sorted = input.slice().sort((a, b) => a - b);

const buckets = sorted.reduce((buckets, item, i) => {
  const lastBucket = buckets[buckets.length - 1];
  if (i === 0) {
    return [[item]];
  }
  const prev = sorted[i - 1];
  if (item - prev > 100) {
    buckets.push([item]);
  } else {
    buckets[buckets.length - 1].push(item);
  }
  return buckets;
}, [])
console.log(buckets);

Answer №3

In this particular solution, we're utilizing the reduce method to manipulate an array based on a specific condition without sorting.

var arrOrg = [100, 200, 300, 500, 600, 700, 1000, 1100, 1200]
arrOrg.reduce(function (acc, item, idx, arr) {
  if (idx) {
    (idx < arr.length && arr[idx + 1] > item + 100) // the spec condition
      ? acc[acc.length] = [item]
      : acc[acc.length - 1].push(item)
  } else acc[0][0] = item
  return acc
}, [[]])

It's important to note that this function results in an empty nested array when called with no input value.

Furthermore, it disregards any need for sorting within the array elements.

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

What is the best way to extract data from individual columns in a PHP multidimensional array?

How can I extract each individual column data from a PHP multidimensional array into a single column array? like $_test = array( array( 'id' => 1001, 'first_name' => 'kalpesh', 'last_nam ...

Grabbing a collection of GeoPoints from a Firebase backend to incorporate into a map's polygon

After researching various StackOverflow discussions, I have managed to develop the following code by combining different methods for retrieving geopoint arrays from Firestore and displaying polygons on an Android googleMap. The activity loads without any e ...

Adjust the size of the font in your Bootstrap Table

I've been utilizing the Bootstrap table feature and it's been fantastic, but I've encountered an issue with changing the font size. I've referred to the example on , however no matter what adjustments I make to the size, it doesn' ...

Having trouble showing an image with jQuery after it has been uploaded

Currently, I have a URL that shows an image upon loading. However, I want to provide the option for users to replace this image using a form input. My goal is to display the uploaded image as soon as it's selected so users can evaluate it. I'm a ...

Assign a class to an element depending on the date

I need to customize a span element in my HTML code like this. html <span class="tribe-event-date-start">September 5 @ 7:00 pm</span> My objective is to identify that specific element based on its date and then apply a class to its parent co ...

Unable to instantiate a class using a module in React

I am on a mission to combine Monaco editor and Convergence in order to create a collaborative editor. To achieve this goal, I am referencing the following repositories and examples: https://github.com/convergencelabs/monaco-collab-ext https://github.com/c ...

Electron Builder reminder: Make sure to include the author's email in the application package.json file

Encountering an Issue During Generation of Build Using Electron Builder. ⨯ Please provide the author's 'email' in the application package.json I attempted to add the email field to the package.json file as well. ...

What makes CVE-2021-33623 susceptible to ReDoS attacks?

CVE-2021-33623 points out that the code snippet below (addressed in this commit, along with test cases) is susceptible to ReDoS vulnerabilities: trimNewlines.end = string => string.replace(/[\r\n]+$/, ''); What makes it prone to ReD ...

What is the best way to retrieve JavaScript Values through Selenium?

Currently, I am working with Java selenium client and running this code snippet. The variable PAGE_NUMBER is assigned a value; however, when using selenium, I'm unable to retrieve it: String script = "var cellValue = selenium.browserbot.getUserWindow ...

Using a Promise to signal the completion of certain tasks

In our application, we have multiple controllers assigned to different tabs/pages. I am looking for a way to signal the completion of a task in one controller so that it can be used in another controller. I believe Promises are the solution for this, and I ...

The $scope.$watch function does not activate with each individual change

Yesterday, I realized that in my angularJS 1.4.8 application, the $scope.$watch doesn't trigger on every change causing a bug to occur. Is there a way to make it work on every change immediately? For example, in this code snippet, I want the function ...

Conceal the second click action within the anchor tag

Is there a way to hide the second click event on all anchor tags except those that trigger popupfun? I have a sample page set up. [Check out the JS Fiddle here][1] http://jsfiddle.net/ananth3087/LgLnpvf4/15/ Link Anchor Tags: The page includes two ...

Angular 4 - The Promising Outcome: How to Retrieve the Value upon Completion

Is there a way to retrieve a value from a promise and store it in a global variable? I've been attempting to accomplish this, but the global variable remains undefined. import { Injectable } from '@angular/core'; import {ActivatedRouteSnap ...

Utilizing objects from a JSON file within an HTML document

I'm currently in the process of creating a comprehensive to-do list, and I want to establish a JSON file that will link all the items on the list together. Despite my efforts, I find myself uncertain about the exact steps I need to take and the speci ...

Vue's computed property failing to compute

I have developed an ecommerce application using Vue.js, and here is a snippet of the store configuration: state: { cart: [], totalItems: { count: 0 } }, getters: { totalItems(){ if(window.localStorage.totalItems){ return ...

Angular.js: The Best Way to Attach a "Change" Event to a Service

Just starting out with angular.js... I have a HTML5 page where I can input new URLs along with names. Now, I need to validate these URLs against a back-end service to see if they already exist. How can I trigger the “onChange” event on the input field ...

Is there a method to extract the y value for a specific x value that is not part of the current data set in a Chart.js graph

I have a set of data points like { x: 5, y: 10 }, { x: 10, y: 15 }, { x: 20, y: 25 }. With Chart.js, I can easily create a chart based on these points. Is there a method to retrieve the y value for a specific x value, such as 13, from the rendered chart? ...

Convert epoch time to HHMM format using JavaScript

I have a specific variable that stores epoch time data. My goal is to showcase the time information in HHMM format. Below you can find the code I am currently using; function convertEpochTimeToDateObj(epoch_time) { var utcSeconds = epoch_time; va ...

Babel Compile disrupts the flow of commands

I'm facing an issue while attempting to launch my development server after Babel successfully compiles my files. However, the command chain seems to halt right after Babel displays the compilation success message. Babel has completed compiling 82 f ...

Exploring the world of jQuery: Toggling radio buttons with variables on click

On the right side, there is a table of data that initially contains certain values, but can be modified using radio buttons and a slider on the left. If you select the first radio button for the "pay in full" option, it will increase the estimated discoun ...