Separate an array into equal parts according to integer values in JavaScript

Although I have not come across any questions that address my specific issue, it may be a duplicate.

Imagine having an array similar to this:

var hundred = [1,2,3,4,5...100] 

This particular array consists of 100 elements, ranging from 1 to 100.

Given an integer value, how can I divide this array into another array with the same number of elements, but distributed evenly in the following manner?

var integer = 2;
var hundred = [50,50,50,50,50,50...100,100,100,100,100,100]

In this scenario, there are 50 elements with a value of 50 and 50 elements with a value of 100 due to the integer being 2.

I struggle with mathematics, so please forgive any inaccuracies. However, I trust you comprehend what I'm trying to convey. The resulting array must retain the same number of indices post-calculation.

Edit (Since formulating clear questions is not my forte, I will provide the code where I require assistance):

I currently possess a frequencybin array (from the AudioContext analyser):

var fbc_array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fbc_array);

This specific array contains a defined number of elements (representing audio frequencies).

Furthermore, I have a spectrum analyzer with a predetermined number of "bars." For instance, if there are only 3 bars, how could I split the fbc_array such that each bar houses an evenly distributed frequency range? For example, with 3 bars, one would contain bass, another the mids, and the last the treble.

To iterate over each bar, I implement a for loop:

for (i = 0; i < bars; i++) {
        bar_x = i * canspace;
        bar_width = 2;
        bar_height = -3 - (fbc_array[i] / 2);
        ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
    }

Answer №1

After carefully analyzing this chaos, here's what I've come up with! It seems like you're struggling to explain your issue clearly. Hang in there and best of luck!

// Define an integer variable
let integer = 3;
let randomNumber;
let output = new Array();

// Function to generate random number within a range
function getRandomIntInclusive(min, max) {
 randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
}

for(let i = 0; i < integer; i++){
  getRandomIntInclusive(1,100);
  for(let j = 1; j < (100/integer); j++){
    output.push(randomNumber);
  }
}

// Note: The array may not always have exactly 100 items
// You can verify using console.log(output.length);
console.log(output);

Answer №2

(Predicting before your recent update).

You want to find a method to estimate a graph by dividing it into bands and replacing each point within a band with the maximum value of that band:

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

Number.prototype.times = function(fn) {
  var array = [];
  for(var index = 0; index < this; index++)
    array.push(fn(index));
  return array;
}



function approximate(source, numBands) {

  var result = [], 
      bandSize = Math.ceil(source.length / numBands), 
      index = 0;
  
  
  while(index < source.length) {
    var chunk = source.slice(index, index += bandSize)
    var maxVal = Math.max.apply(null, chunk);
    
    // To get an average instead of maximum, use below line
    // maxVal = chunk.reduce((x, y) => x + y) / chunk.length;
    
    result = result.concat(bandSize.times(i => maxVal));
  }
  
  return result;

}



sourceArr = 20..times(i => 10 + Math.floor(Math.random() * 80));

resultArr = approximate(sourceArr, 4);

document.write('<pre>'+JSON.stringify(sourceArr));
document.write('<pre>'+JSON.stringify(resultArr));

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

Error encountered in NEXT JS: Unable to parse URL from /api/projects or Error message: Failed to connect to 127.0.0.1:3000

Currently utilizing: export const getStaticProps = async () => { export const getStaticPaths = async () => { and accessing my API (pages/api/projects/) created with Next.js on my local host const res = await fetch("http://localhost:3000/api/ ...

Searching for a specific element within an array in MongoDB

In my MongoDB collection, I have a straightforward array: "_id": "5669b4930874f8d01f7676da", "cars": ["BMW", "Audi", "VW"] My goal now is to check if the document contains "Audi". After going through all array-related questions on SO, I realized they mos ...

Utilize PHP to import hierarchical JSON data into MySQL database along with establishing relationships

Is there a straightforward solution to importing nested JSON data into multiple MySQL tables? The challenge is that JSON lacks bidirectional relations, so they need to be generated automatically. Check out this sample data: [ { "targetgro ...

Leveraging Google Sheets as a Dynamic Database with Ajax

I found a helpful guide on using Google Sheets as a database with Apps Script and ajax. Here is the link. I understand that I need to include 'Google Sheet/Apps Script Code' in a spreadsheet. However, I'm unsure about what needs to be place ...

Utilize Symfony filtering alongside AJAX functionality with the added feature of the KnpPaginatorBundle

When filtering data using ajax, I encounter an issue with pagination in Symfony and KnpPaginatorBundle. The pagination works fine when displaying the data without any filters. However, after applying a filter using ajax, clicking on page 2 of the paginati ...

Having trouble iterating through an array of objects in Vue?

Having trouble looping through an array of objects in Vue3 <template> <div class="shadow-xl w-96 h-96 md:h-[600px] md:w-[600px] lg:my-12 lg:w-[700px] lg:h-[700px] rounded-md" > <button @click="getData">Get ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

coming back to the cordova application after using the browser

I recently developed a basic app using the ionic framework. There is a feature in the app that opens an external payment gateway in a system browser to process payments. After successful payment, a script on my server sends an HTML page to display a succes ...

Adding a background image to a box in MUI is a simple task that can enhance

I've been attempting to include a background image in the Box component of mui, but I can't seem to get it to work. Here is the code I've been using: const Main = () => { return ( <Box sx={{backgroundImage:'images/cove ...

The essential criteria for script tag and page validation requirements

There are instances where I have pages that contain only a script without any content (such as sending data through postMessage and then closing itself). In these cases, is the page considered valid with just <script>doSomeStuff</script> or do ...

Is the code failing to refresh the browser when the file is modified?

Does anyone know how to reload the browser when a file changes? var changing = require('changing'); var watcher = changing( { interval: '0s' }); watcher.add("/home/diegonode/Desktop/ExpressCart-master/routes/2.mk"); watcher.on(& ...

Ways to Enhance jQuery Efficiency in a Broader Sense

Utilizing jQuery functions is a common practice for us. However, there has been talk about its impact on performance. While it is simple to write, understand, and maintain, some say that it is slower compared to using traditional raw JavaScript code. But ...

What is the best way to create a simulation of a NOR gate using JavaScript?

Can a NOR gate be emulated in JavaScript? It seems that the language only supports AND and OR gates at this time. ...

Extract the values of a PHP object and store them in an array

How can I store the output from the initial echo $zip as a simple integer stack in an array? I have tried various accessors like [], {}, and others but haven't had any luck. Thank you! This is my current code: $userZip = new ZipCode($userZip); $theZ ...

ways to deliver a message from server to client's body

Here is the Java server code I am using: private Response createError(int code, String error) { logger.error(error); return Response.status(code).entity("{ \"errorMsg\": \""+error+"\"}").build(); } And this is the client code: ...

Instructions on how to insert information into an array by clicking a button

As a newbie JavaScript programmer, I am struggling to figure out how to make my code work as a function. I want to update the ajax_data array every time I click the add row button. Fresh JS coder looking for some guidance. var ajax_data = [{ Type: "A ...

In jqGrid's gridComplete event, we can use the getRowData method to retrieve the value of a

Seeking guidance on extracting variables from jqGrid getRowData method While iterating through rows, I simply want to retrieve the ID and Phrase column values into separate variables gridComplete: function () { var allRowsInGrid = $('#list'). ...

Unable to assign to array in VBA

There seems to be an issue in my code that I can't figure out. Specifically, the line "Key = decode.GetKeys(issue)" is causing the error mentioned in the title of this question. Public Sub Import_JSON_From_URL(url As JiraJSONGet) ThisWorkbook.Sheets ...

Is it good practice to have empty arrays positioned before calls and timeouts when utilizing class variables?

I am facing some unusual challenges. Seeking assistance. I have a database object that extends my other class objects, allowing me to attach result sets onto class variables and access results statically from anywhere in the application. Below is my "sele ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...