Using array index to group colors in Javascript

Below is an array that I have:

const colors = ['#54AAED', '#7BEA6B', '#f8b653', '#ff5584']

I am working on creating a function that can return a color based on the parameter group and index. For example:

function groupColor(i, group) {}

The expected output from the function would be:

groupColor(0, true); output <== '#54AAED'
groupColor(1, true); output <== '#54AAED' Minus 10% RGB

In this case, for each group, Index 0 will be #54AAED, Index 1 will be #54AAED with 10% opacity subtracted, Index 2 will be #7BEA6B, and Index 3 will be #7BEA6B with 10% opacity subtracted, and so on... Here's what I have done so far:

function hexToRgb(hex, opacity) {
  return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(opacity||1).join(',') + ')';
}

function generateColor({ i, group }) {
  if (group) {
    console.log('should group...')
  }
  const isEven = i % 2 === 0

  console.log('index', hexToRgb(palette[i], 0.9))
  return hexToRgb(palette[i])
}

My approach was to check if the index is odd and group by intervals of 2 indexes if the boolean is true. However, I am unsure about how to proceed with grouping in intervals of 2 and setting the opacity to 0.9 on the second iteration...

Example Usage:

const colors = ['#54AAED', '#7BEA6B', '#f8b653', '#ff5584']
const groupMe = ['one', 'two', 'three', 'four']
groupMe.map(entry => {
 return generateColor(i, true)
})
// expected output
'one' <== '#54AAED' opacity 1
'two' <== '#54AAED' opacity 0.9
'three' <== '#7BEA6B' opacity 1
'four' <== '#7BEA6b' opacity 0.9
and so on...

Answer №1

To determine if the number is even, simply go to the previous index and employ a ternary operator to set the opacity. Here's an example using React:

const Component = React.Component
const palette = ['#54AAED', '#7BEA6B', '#f8b653', '#ff5584', '#d743c4', '#76bbf1', '#95ee89', '#f9c575', '#ff9d6d', '#ff779d', '#df69d0', '#9178ec'];
function hexToRgb(hex, opacity) {
  return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(opacity||1).join(',') + ')';
}

function generateColor({ i, group }) {
  const isEven = i % 2 === 0
  if (group) {
   return hexToRgb(palette[isEven ? i : i - 1], isEven ? 1 : 0.9)
  }
}

class App extends Component {
  render() {
    const iterations = 10;
    return (
      <div style={{ textAlign: 'center', width: '50%', margin: '0 auto' }}>
        {Array.from(Array(iterations), (_, i) =>
          <div style={{ width: 300, height: 10, marginTop: 10, backgroundColor: generateColor({ i, group: true }) }} />           
        )}
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('mount')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="mount"></div>

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

Step-by-step guide for properly transferring PHP MySQL data to ChartJs

I am looking to create bar charts and pie charts using ChartJs, with data fetched from php and mysql. Specifically, I want to generate a bar chart that illustrates the statistics of male and female students, along with the total number of students. The des ...

Using Sweetalert2 to send data via AJAX POST request

Recently, I've been incorporating SweetAlert2 into my project and I want to create an "Add Note" feature. The process involves the user clicking a button, being directed to a page, and then the following script is executed: <script>swal({ ...

Looking to construct a multidimensional array in JavaScript for efficiently reading arrays along with their corresponding options?

I am looking to create a multidimensional array in JavaScript to store questions along with their related options. Here is my current code snippet: demoArray[i] = new Array(); var id=results.rows.item(i).del_ques_id; demoArray[i]["question"] = results.row ...

What could be causing React to display a TypeError: Unable to read 'join' property of an undefined value?

I am working on displaying a list of books with the names of their authors below. In cases where there are multiple authors, I am trying to separate their names using the .join() method. Below is a snippet of the code without using .join(): <select ...

When delving into an object to filter it in Angular 11, results may vary as sometimes it functions correctly while other times

Currently, I am working on implementing a friend logic within my codebase. For instance, two users should be able to become friends with each other. User 1 sends a friend request to User 2 and once accepted, User 2 is notified that someone has added them a ...

Creating a template based on an object type in JavaScript with Angular: A step-by-step guide

I have a collection of objects, each with a property indicating its type. Here's an example: [ { "type" : "date", ... },{ "type" : "phone", ... },{ "type" : "boolean", ... } ] I'm ...

Embed Socket.IO into the head tag of the HTML document

After working with socket.IO and starting off with a chat example, my chat service has become quite complex. The foundation of my code is from the original tutorial where they included <script src="/socket.io/socket.io.js"></script> <scrip ...

How can you prevent videos from constantly reloading when the same source is used in multiple components or pages?

How can we enhance loading performance in Javascript, React, or Next JS when utilizing the same video resource across various components on different pages of the website to prevent unnecessary reloading? Is there a method to store loaded videos in memor ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Tips for arranging HTML elements in a horizontal line, even if they belong to different parent elements

My HTML document features a sticky header and footer, with a div below the header that sticks to it to eventually hold tabs above a form. I've been struggling to align the form vertically below this div. The issue arises because the tab div lacks a sc ...

What steps can be taken to ensure that AngularJS does not detach a form input's value from its model if it is invalid?

While working on a form implementation in AngularJS, I encountered a baffling behavior that has left me puzzled. It seems that whenever I set ng-minlength=5 as an input attribute, AngularJS disconnects the value until it meets the length requirement. Thi ...

The secondary angular button is failing to execute the function

Can someone help me with a small issue? I have two buttons on a webpage that should both contact a server. However, only the first button sends a HTTP request when clicked. <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8 ...

Exploring the potential of utilizing records within deepstream.io

Lately, I've been delving into the world of records and I find myself pondering on the practical limitations when it comes to the size of a json structure. Is there a recommended maximum length? Can you store an entire chat history as an (anonymous) r ...

Navigating through items and organizing based on several criteria

In JavaScript, I am currently learning about accessing objects and sorting them based on multiple conditions. As a beginner in JavaScript, this may seem like a very basic question to some. My task involves sorting based on the 'status' field. va ...

Masking input text to allow numbers only using either javascript or jquery

I have experience with javascript and jquery. My goal is to create a masking template for <input type="text"> This template should only accept numbers and automatically format the input with dashes after every two numbers typed. The desi ...

The closing tag for the "body" element was excluded even though OMITTAG NO was specified

While attempting to validate my contact support page, I encountered the following errors: Omission of end tag for "body", even though OMITTAG NO was specified ✉ You may have forgotten to close an element or intended to self-close an element by ending ...

Extracting all usernames of members present in a specific voice channel and converting them into a string using Node.js on Discord

Hey everyone, I'm looking for a code snippet that will help me retrieve all the members from a specific voice channel by using its ID. I also need to extract and store the usernames of these members who are currently in that particular voice channel w ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...

What are the steps to showcase a webcam stream in GLSL by leveraging Three.js?

One method of displaying a webcam video using ThreeJS involves creating a video texture, as shown below: video = document.getElementById( 'video' ); const texture = new THREE.VideoTexture( video ); texture.colorSpace = THREE.SRGBColorSpace; const ...

JSON variable unable to be stored in database

I have a Django application where I am attempting to save the configuration of a gridster widget as a JSON variable in the database. However, when I click the "Update" button on the webpage, no value is stored in the database. Below is my JavaScript code ...