What method can be used to segment data in an array while also factoring in the preceding value?

I currently have an array named targetPercentage.

targetPercentage = [0,33,77,132]

Is there a way to divide it into chunks of size 2 while also including the previous value? Additionally, is it possible to convert it into a JavaScript object array with corresponding properties?

Here's an example of the desired output:

[0,33]
[33,77]
[77,132]

Here's an example of converting it into an array of objects:

thresholds : [ {from:0,to:33},{from:33,to:77},{from:77,to:132} ] 

I'm looking for a solution similar to this question but with the inclusion of the previous value.

Answer №1

To build an array from the ground up, utilize Array.from to retrieve the ith element along with the i + 1th element during each iteration in order to form the objects:

const targetPercentage = [0,33,77,132];
const result = Array.from(
  { length: targetPercentage.length - 1 },
  (_, i) => ({ from: targetPercentage[i], to: targetPercentage[i + 1] })
);
console.log(result);

Alternatively, if you desire an array of arrays:

(_, i) => ([ targetPercentage[i], targetPercentage[i + 1] ])

Answer №2

let targetValues = [20, 40, 60, 80]

let levelLimits = []
for (let j = 0; j < targetValues.length - 1; j++) {
let interval = {
  start: targetValues[j],
  end: targetValues[j + 1]
 }
 levelLimits.push(interval) 
}

Answer №3

Give this a shot:

function binaryConvert(data) {
  let output = []

  for (let i=0; i<data.length-1; i++) {
    output.push({
      start: data[i],
      end: data[i+1]
    })
  }

 return output
}

Answer №4

When using the array function slice(initial,count), it will slice the given array into 3 chunks, each containing 2 elements.

The temporary array will contain [0,33], [33,77], [77,132]

var i, j, tempArray, chunk = 2;
result = [];
for (i = 0, j = targetPercentage.length; i < j - 1; i++) {
    tempArray = targetPercentage.slice(i, i + chunk);
    result.push({ from: tempArray[0], to: tempArray[1] });
}
console.log(result);

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

Guide on converting retrieved data from MySQL into JSON using PHP

I'm currently working on converting data retrieved from a MySQL database into JSON format using PHP. Below is the code snippet I am utilizing: try { $statement = $db->prepare($query); $result = $statement->execute($query_params); $ ...

Challenge with sorting an array using binary search

int arr[] = {21, 44, 56, 76, 89, 91, 102, 120, 143, 167, 242, 291}; // This array has a length of 11. int goal = 143; int i = (arr.length - 1)/2; int upper = arr.length - 1; int lower = 0; int found = 0; boolean foundYes = false; int j; while (foundYes = f ...

Generate visual at reduced quality (three.js)

Is there a way to reduce the resolution of my rendered canvas similar to how it can be done with the Blender camera resolution? I came across a suggestion to use renderer.setDevicePixelRatio(window.devicePixelRatio) However, when I tried this, the objec ...

When a function inside React uses this.props, it won't trigger the corresponding function

I am currently developing a Checklist using React and MaterialUI that consists of two components. One component is responsible for managing the data, while the other component allows for editing the data. However, I have encountered an issue where the func ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more ...

Protected node.js REST API

I want to ensure the security of a restful API and aim to keep it simple and stateless. What is the best way to store, generate, and authenticate API keys? I was considering using node-uuid to generate keys, storing them in Redis, and then authenticating ...

What is the best way to crop a page?

Running a React application, I am integrating a page from an external ASP.NET app. To achieve my goal of extracting only a section of the page rather than the entire content, I am unsure if it is feasible. Specifically, I aim to extract just the body of th ...

Numerous query parameters sharing identical names

I am seeking information on how EXPRESS handles multiple query parameters with the same name. Despite my research efforts, I have been unable to find a reliable source on this topic. Specifically, I am interested in how EXPRESS would interpret a URL such ...

Create dynamic animations using AngularJS to transition between different states within an ng-repeat loop

Here's a simplified explanation of my current dilemma: I have an array containing a list of items that are being displayed in an Angular view using ng-repeat, like... <li ng-repeat="item in items"> <div class="bar" ng-style="{'width ...

JavaScript JCrop feature that allows users to resize images without cropping

I'm currently attempting to utilize JCrop for image cropping, but I'm running into frustratingly incorrect results without understanding why. The process involves an image uploader where selecting an image triggers a JavaScript function that upda ...

What is the best way to retrieve the value from a textfield in one module and use it in a

How can I access the value of a textField in another module within React.js without importing the entire textfield component? What is the most effective approach to get access to the value variable in a different module? Below is a sample functional textF ...

Discover the Magic Trick: Automatically Dismissing Alerts with Twitter Bootstrap

I'm currently utilizing the amazing Twitter Bootstrap CSS framework for my project. When it comes to displaying messages to users, I am using the alerts JavaScript JS and CSS. For those curious, you can find more information about it here: http://get ...

circumvent the JSON web token to perform a POST request using a web browser

While looking at the network tab, I came across this request: https://i.sstatic.net/hNqJD.png I attempted to use to post to the request, but it was unsuccessful. Can someone explain the authorization process involved in this request? Is it a security me ...

Angular firing a function in the then clause before the initial function is executed

I have a situation where I need to make multiple service calls simultaneously, but there is one call that must be completed before the others are triggered. I have set it up so that the other calls should only happen after the .then(function() {}) block of ...

Finding the Right Path: Unraveling the Ember Way

Within my application, I have a requirement for the user to refrain from using the browser's back button once they reach the last page. To address this, I have implemented a method to update the existing url with the current page's url, thereby e ...

Activate the angular function

In the controller below, there is a function that should be triggered when the link is clicked: <a id="1" href="" name="xxx" ng-click="searchall(id)">sample link</a> ng.controller('SearchResultController', ['$scope', &apos ...

Is the variable not being initialized outside of the function?

I'm really struggling with this async issue. I can't seem to get it to work because the summonerData array is not being set. I have a feeling it has something to do with async, but I'm not sure how to troubleshoot it. var summonerName = req ...

Updating Information Using JQuery

In my view, there is a partial view that displays details of open IT Tickets. Clicking on an open ticket loads the partial view with ticket details and comments using JQuery/Ajax. However, I'm facing an issue where if a new comment is added to a tick ...

Difficulty encountered when attempting to implement custom filtering based on condition in HTML using Angular

I'm still new to angular, so please bear with me if this question seems trivial. I have a collection of integers in my controller and I need to filter it to only show items that meet a certain condition. Initially, I attempted the following: <div ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...