Using Conditions in a Javascript For Loop

I would like to utilize a for loop to achieve the following task.

Within an array, I have a predefined set of values representing hex colors for a chart. My goal is to extract a specified number of those values using the loop with two options.

  1. If the number of values in the defined color set is less than the requested quantity, the loop should begin again from the first value once it reaches the last one.

  2. Less critical but potentially useful is the ability to start fetching values at any index within the default values set and apply the same cycling condition as in option #1 – looping back to the beginning when reaching the end of the color array.

Here's some initial code along with sample data to illustrate my requirements.

var defaultColors = ["#90CAF9","#B39DDB","#7E57C2","#78909C","#AED581"] ;
var chartData = [12,24,30,40,15,23,35] ;

var dynamicColors = function (a) {
    var colors = [];
    for(i=0;i<a;i++){
        colors.push(defaultColors[i]);
    }
    return colors;
}

And here is how the colors are being called

backgroundColor: dynamicColors(chartData.length),

In the above example, there are more data points than available color values, necessitating the loop to restart from the beginning of the color array.

Expected result for #1 - Looping through the array from the start.

["#90CAF9","#B39DDB","#7E57C2","#78909C","#AED581","#90CAF9","#B39DDB"]

Expected result for #2 - Starting from a specific index.

["#7E57C2","#78909C","#AED581","#90CAF9","#B39DDB","#7E57C2","#78909C"]

Answer №1

Utilize the modulo (also known as remainder) operator `%` in conjunction with the list length to achieve a looping effect within the list:

var defaultColors = ["#90CAF9", "#B39DDB", "#7E57C2", "#78909C", "#AED581"];
var chartData = [12, 24, 30, 40, 15, 23, 35];

var dynamicColors = function(a) {
  var colors = [];
  for (i = 0; i < a; i++) {
    colors.push(defaultColors[i % defaultColors.length]);
  }
  return colors;
}

console.log(dynamicColors(10))

If you wish to commence at a different point, simply adjust it in i and apply the mod operator once again:

var defaultColors = ["#90CAF9", "#B39DDB", "#7E57C2", "#78909C", "#AED581"];
var chartData = [12, 24, 30, 40, 15, 23, 35];

var dynamicColors = function(a, start) {
	var colors = [];
	for (i = 0; i < a; i++) {
		colors.push(defaultColors[(i + start) % defaultColors.length]);
	}
	return colors;
}

console.log(dynamicColors(7, 3)) // seven values starting at index 3

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

Can you please provide a step-by-step guide for using socket.io with TypeScript and webpack, after installing it

Currently, I am experimenting with TypeScript in conjunction with node.js, socket.io, and webpack. To facilitate this setup, I have configured the webpack.config.js, tsconfig.json, and tsd.json files. Additionally, I acquired the typings file for socket.i ...

Display intricate header and preview in a printed datatable

Hey there, I've been using the Datatable plugin and it's really great. However, I've come across a problem with complex headers like this: <thead> <tr><td>some text</td></tr> <tr><td>some te ...

How come the POST request does not return the JSON according to the specification in my Mongoose schema definition?

I'm encountering an issue with running a POST request on Postman. After running the POST request, I am only receiving a partial schema back, instead of the entire JSON as defined in my Mongoose schema. Here is the relevant code snippet: Model: &apos ...

Exploring the World of Github on Windows: Understanding the 'master' and 'gh-pages' Branches

I have developed a simple jQuery plugin and uploaded it to Github. I am using both the Github website and Github for Windows to manage this project. However, when I try to include the .js or .css files from Github using the Raw links, my browser fails due ...

Is there a way to easily deserialize a JSON object that doesn't have a specified name and is constantly

In the JSON provided below, you will find error messages for various properties: { "username": [ "A user with that username already exists." ], "ruc": [ "user with this RUC already exists." ], "code": [ "user wi ...

If a checkbox is checked, then the value in the textbox should be multiplied by 0

I'm faced with a challenge involving a non-clickable textbox that is meant to hold a running total. Each time a checkbox is clicked, its value should be added to the total in the textbox. However, I am now struggling to figure out how to perform mult ...

What is the best way to test for errors thrown by async functions using chai or chai-as-promised?

Below is the function in question: async foo() : Promise<Object> { if(...) throw new Error } I'm wondering how I should go about testing whether the error is thrown. This is my current approach: it("checking for thrown error", asy ...

Building a custom login page with axios in a react-redux application

I've encountered an issue with my login page. When I click the submit button, it does not redirect to the main Dashboard page. Check out the code below for authentication/login.js: import React, { Component } from 'react' import { Field, ...

Navigating following a JQuery AJAX request in PHP

After clicking the login button, I utilize JQuery's POST method to retrieve data from login.php to check if the login was successful. If it fails (no user found), the appropriate message is displayed. However, when attempting to redirect a user (whic ...

How to retrieve an array from a JSON object with JavaScript

After receiving an object from the server, I am specifically looking to extract the array ITEMS. How can I achieve this? I attempted using array['items'] but it did not yield the expected result and returned undefined { "items": [ { ...

Integrating a YouTube video in the Google Maps info window with the help of Ajax technology

Currently working on a project for Udacity, my goal is to develop a neighborhood map using Google Maps API alongside Knockout and Ajax to integrate with another 3rd party API. A unique aspect of my approach is focusing on bars in the neighborhood and utili ...

struggling to send variables to jade templates with coffeescript and express.js

As a newcomer to node and express, I am currently building the front end of an application that utilizes jade as its templating engine. Despite extensive searching online and within this community, I have not been able to find a solution to a particular is ...

Encountered an issue while trying to add images and text simultaneously in asp.net

I am trying to modify my code by adding an image along with the text. Here is the updated code: $(".ChatSend").click(function () { strChatText = $('.ChatText', $(this).parent()).val(); var recievertext= $('.ausern ...

Automatically submitting the selection when it changes

I am facing an issue with a selection form that is supposed to update the database on change using jQuery, but it seems like nothing is happening. Can anyone provide assistance with this problem? <SELECT name='status' id='status'> ...

Execute Javascript after modification of the DOM

I have developed two custom directives known as app-content and app-content-item. These directives are intended to be utilized in upcoming projects to provide a basic structure with simple styling. They will be incorporated into a module and should be nest ...

Can you share the method for concatenating an object at a specific index within an Array using JavaScript?

Currently, I have an array arr = [object1, object2, object3]. After removing the second index, the array now looks like arr = [object1, object3], and I am looking to add back the removed object2 at its original position in the array so that it becomes a ...

What is the best method for isolating a single object from a collection of objects?

How do I go about filtering out the objects from an array that have admins->member = 11? In this scenario, the resulting array object would only contain the first object that starts with [245]. Array ( [245] => stdClass Object ( ...

Error: Unable to access property 'camera' as it is undefined

After implementing the Raycaster from Three js to detect collision following a MouseMove event, I encountered an error: Cannot read properties of undefined (reading 'camera') Here is the code snippet causing the issue: bindIFrameMousemove(if ...

Excessive JSON formatting is consuming an excessive amount of storage space

As I work on developing a website that recommends locations to visit in NYC, I am facing an issue with saving JSON data in local storage. My goal is to allow users to add their own suggestions and eventually integrate MongoDB into the site. To build the si ...

Delete elements from a dynamic list

I am working with a dynamic array containing chat messages, structured like this: { id:1, message: bla-bla }, { id:2, message: bla-bla }, { id:1, message: bla-bla }, { id:1, message: bla-bla }, { id:3, message: bla-bla }, { id:4, message: bla- ...