Update the predefined set of numbers with a flexible array size

I'm currently exploring ways to dynamically replace the fixed values 1, 2, and 3 within this GUI interface with a range of numbers based on the size of an array. I aim for the GUI to automatically adjust as the array is updated, without the need for manual intervention each time. https://i.sstatic.net/BSYYY.png

The challenge lies in the fact that these values are individual objects within the GUI, hence using a simple array of numbers proves cumbersome. This is the code snippet in question:

gui.add(data, 'system', {
  "1": 0,
  "2": 1,
  "3": 2
})

Imagine working with a random array populated with arbitrary data like so:

var arr = [];
for (var i = 0; i<51;i++){
    arr.push("element");}

This array contains 51 elements, and my goal is to display numbers "1", "2", "3", "4", "5", "6" (consistent with 10-element intervals) in the GUI without causing any disruptions. The intention behind dividing by 10 is to streamline the user experience by offering just 6 clickable options instead of all 51.

What steps should I take? Your insights would be greatly appreciated. For reference, here is the fiddle containing my code: FIDDLE

EDIT: To clarify further, my current setup involves hardcoding the values 1, 2, and 3 into the object as follows:

gui.add(data, 'system', {
  "1": 0,
  "2": 1,
  "3": 2
}).name('system #').onChange(function(value) {
  updateSets(value);
});

However, my objective is to automate this process whereby the numerical values correlate with the length of an array. With a 3-element array, it should input those values accordingly. Yet, if the array expands to 51 elements, I seek a method to limit the displayed numbers under the system object to just 6 - excluding the one leftover.

Answer №1

To generate an object with properties and values equal to the length of an array, you can leverage the Array.prototype.reduce() method.

Start by creating a plain object. Use Object.entries() and a for..of loop to assign properties and values to the object up to a specified variable n.

Then, utilize Array.prototype.slice() to extract properties and values from the generated object based on ranges specified by variables n and x.

var arr = [];
for (var i = 0; i < 51; i++) {
  arr.push("element");
}

var obj = arr.reduce(function(obj, element, index) {
  obj[index + 1] = index;
  return obj
}, {});

function getObjProps(from, to, obj, res) {
  let it = void 0;
  if (from) {
    it = Object.entries(obj).slice(from, to);
  } else {
    it = Object.entries(obj);
  }
  for (let [key, value] of it) {
    if (+key <= to) {
      res[key] = value;
    } else {
      break;
    }
  };

  return res
}


var curr = getObjProps(null, 6, obj, {});

console.log(curr);

var next = getObjProps(6, 12, obj, {});

console.log(next);

for (let i = 12; i < arr.length; i += 6) {
  console.log(getObjProps(i, i + 6, obj, {}))
}

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

How can one implement a matrix transformation and establish it as the default state in ThreeJS?

I am working with a group of THREE.Mesh objects and my objective is to apply a rotation using the code snippet group.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI / 2) );. Afterwards, I want to set this resulting matrix as the default state for t ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

The error message states that the type '[ListB]' does not have a member called 'books'

Encountering an error stating "Value of type '[ListB]' has no member 'books'" from the function below at the line "books = hardfictList.books" func retrieveTop100FHCDataFromAPI() { let url = myUrl AF.reque ...

Having trouble interpreting bar chart with d3js v7. Issue: <rect> attribute height not meeting expected length, displaying as "NaN"

Hello amazing community at Stack Overflow, I've been working on a project for my university where I am trying to create a bar chart using d3v7. I have been following the example from the Blocks but I keep encountering an error mentioned in the title ...

Issue with switch statements in PHP/JavaScript causing unexpected 'undefined' behavior

Exploring a switch statement: var currency = ""; switch (row.currency) { case 1 : currency = "&pound;"; break; case 2 : currency = " &#36;"; break; case 3 : currency = "&euro;"; break; default: currency = "&po ...

Retrieve JSON data from an object using the Amplify Storage feature

I recently retrieved data from an object in an S3 Bucket using Amplify. export function amplify() { let key = "68a92d44-f25a-4bd8-9543-cc95369ae9a0"; return Storage.get(key + ".json", { download: true }) .then(function(result) { return ...

There is a problem with creating the dynamic 2D array

Struggling to create a dynamic 2D array through a function, but encountering errors when trying to add elements. Error An unhandled exception has occurred: 0xC0000005: Access violation writing location 0xcdcdcdcd. CreateDynamicArray() short int** Cre ...

TranslateY animation glitching

I need help with expanding a box to 100% height after click, then collapsing and sticking to the bottom. I created a function in Vue framework to handle the animation, but it's not working smoothly. How can I make it less buggy? Check out the demo her ...

iframe: retrieve current iframe

Currently, I'm working on a page that contains multiple iframes. Only one iframe is active at a time, and I need to be able to determine which one is currently active. I attempted using document.activeElement.id, but it only returns the correct resul ...

What is the best way to hide the next/previous tabs once the jQuery dataTable has been set up using jSON data

Setting up a jQuery table using JSON data. Despite knowing that there will only be one row, the next/previous tabs are still displayed after the table. Is there a way to remove them? Here is the code for the table: table = $("#retrievedTable").dataTabl ...

Page encountering NextJS cors error, while API route remains unaffected

In my Next.js application, I have encountered an issue where executing a call to fetch a page from an external website works perfectly fine when done from the backend through an API route. However, when attempting the same action from the frontend, I encou ...

Tips on saving text from a file into an array and displaying it at specific positions in Java

How do I extract lines from a text file and store them in an array to print at specific locations? My coi.txt file has 15 lines that I want to display at specified positions through iteration. Can someone please assist me with this task? Thank you for yo ...

What is the best way to retrieve data from an Express endpoint within a React component?

I am working on integrating a React component with an Express endpoint that returns the string "sample data". The goal is to call this endpoint from my React app, store the text in state, and then display it on the screen. Here is my component: class App ...

Finding and removing the replicated keys within a JSON array while also retrieving the corresponding JSON path

I have a JSON object that looks like this: {"response":{"result":{"Leads":{"row":[{"LEADID":"849730000000063017","SMOWNERID":"849730000000061001"},{"LEADID":"849730000000063015","SMOWNERID":"849730000000061001","HIII":"hello"},{"LEADID":"84973000000006 ...

Separating array data within a SQL field into a new table with individual rows

I am in need of extracting a list of user IDs (course_user_ids) that are currently stored in a single field within a larger table structure. Within my courses table, the information is structured with course_id and course_students columns as shown below: ...

Unable to Access Camera in Angular5 Instascan: <video> Issue

Having Trouble Displaying Camera View with Angular5 and Instascan, Despite Camera Being On app.component.ts constructor(){ this.Instascan= require('instascan'); let scanner = new this.Instascan.Scanner({ video: document.getElementById("pr ...

Change the class of the div when the first div is selected

My goal is to switch the class of the #klapp element (from .klapp to .klappe) whenever a click event happens inside the #label-it container, including when the #klapp element itself is clicked. The challenge is that I am not able to use unique IDs for each ...

How can the loop be counted to display an array of images along with custom metadata?

I'm facing a challenge that seems to be quite basic, yet I can't seem to find the solution on my own. Here's what I need help with: On a website, I have an image gallery where each image can be marked as "featured" using a custom meta field ...

Updating the color of text when clicking on a link using javascript

I am facing an issue where I cannot seem to change the text color using JavaScript. The functionality to show and hide div tags is working perfectly, but changing the color seems to be a challenge. It's worth noting that there are no styles defined fo ...

Display arrays vertically within each column using PHP

I have an array with both rows and columns specified. My goal is to print each column as a list within a loop. $row = 3; $col = 4; $arr=[ '1' , '2' , '3' , '4', '5& ...