Find the hex code corresponding to the darkest color in the JSON response

I'm working with a json response that contains various vehicle objects, each with a hexcode value representing the color of the vehicle:

[ { "name":"Ford", "hexCode": "4B1A1F"},
    { "name":"BMW", "hexCode": "FFFFFF"},
    { "name":"Fiat", "hexCode":"000000"}
]

My goal is to determine which hexcode corresponds to the darkest color among them. Since not all manufacturers use #000000 for black, I need to find a way to identify the darkest color.

Is there a solution to achieve this using regex or JavaScript?

Answer №1

Because not all manufacturers opt for #000000 as their representation of black.

Once you establish your own definition of what truly constitutes the "darkest", navigating this issue will become simpler. Despite the initial hurdle of inaccurate source data, it should still be feasible to utilize it for your specific requirements. Since your primary concern is luminance rather than color itself, experimenting with converting the provided color value to grayscale and selecting the closest one to 0x00 might prove beneficial in determining the darkest shade.

Answer №2

Avoid using regex if you are working with JavaScript. Instead, store the JSON data in a variable and let JavaScript handle the parsing. Then, convert each color to HSL format and determine the minimum lightness value.

In the world of colors, HSL (Hue, Saturation, Lightness) is a color model that provides a more objective way to evaluate the "darkness" of a color.

Answer №3

One way to determine the color with the lowest luminance (Y) value is by comparing the RGB colors provided in hexadecimal format. The calculation can be done using the formula:

Y = 0.299R + 0.587G + 0.114B

To find this minimum value, you can follow these steps:

function findLowestLuminance(hexValue){
  return hexValue.match(/[0-9a-fA-F]{2}/g)
                 .map(h => parseInt("0x"+h))
                 .reduce((r,c,i) => (r[3] += r[i]*c, r),[0.299,0.587,0.114,0])[3];
}

var data = [ { "name":"Ford", "hexCode": "4B1A1F"},
             { "name":"BMW", "hexCode": "FFFFFF"},
             { "name":"Fiat", "hexCode":"000000"}
           ],
  result = data.map(d => Object.assign({},d, {Y: findLowestLuminance(d.hexCode)}))
               .reduce((p,c) => p.Y <= c.Y ? p : c);

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

Having trouble retrieving data from the PokeAPI

Currently, I am experimenting with PokeAPI for educational purposes and attempting to run the following code: const express = require('express') const https = require('https') const app = express() const port = 3000 app.get('/&apo ...

What is the process for inserting or removing a row with Javascript?

Currently, I am in the process of working on some HTML/PHP code which is displayed below. <h3 style="text-align:center;margin-top:45px;">Sitting Days</h3> <div class="sitting-days" style="display:flex; justify-content:center; margin-bottom ...

Attempting to extract the cell information and choose an option from a cell using the Tabulator program

I've been using Tabulator, which is an amazing tool, but I've run into a little trouble. I'm trying to add an HTML Select in each row, with options specific to each record. When I change the select option, I call a function and successfully ...

Unfulfilled expectation of a promise within an array slipping through the cracks of a for loop

I have a function that generates a Promise. Afterward, I have another function that constructs an array of these promises for future utilization. It is important to note that I do not want to execute the promises within the array building function since so ...

The console.log() function does not accurately display the true value

While looping through a list and using a @click function to update other elements, I have encountered an issue with the index values bound to selectedFixtures. Each time I click on an element, it initially prints out [], and then on subsequent clicks, it ...

Insert a new item into an existing list using jQuery

I am looking to enhance user experience by allowing them to easily add multiple sets of inputs with just one click. I have been experimenting with jQuery in order to dynamically insert a new row of input fields after the initial set. My current approach i ...

AngularJs Number Formatting: A Step-By-Step Guide

Is there a way to format a number from 10000 to 10,000.00 using only HTML and the ng-Model directive, without involving the controller file? I attempted to achieve this in the controller file through logic, but it always returns the number in the "10,00 ...

What's the deal with $routeProvider in angularJS?

I'm having some trouble with my simple web app that I'm trying to update using route provider. Everything works fine when I click on the list items on the page, but when I refresh the page, I get a 404 error. It seems like it's trying to acc ...

Having trouble accessing the property of undefined in material ui cards

Currently, I am incorporating Material UI cards into my React project. One issue I encountered is trying to implement two functions, onMouseOver and onMouseOut, in my cards. However, when I run the code, I receive an error message stating "Uncaught TypeE ...

Ways to eliminate numerous if statements in JavaScript programming

Here is the code snippet I'm working with: a = [] b = [] c = [] useEffect(() => { if(isEmpty(a) && isEmpty(b) && isEmpty(c)) { data.refetch() } if(data.isFetching){ //do something } if(response.isFetching){ //do som ...

Leveraging Bootstrap without an internet connection

In the process of developing a desktop application with Electron, I have decided to incorporate Bootstrap for its design elements. Yet, my ultimate goal is to ensure that the app remains functional offline once it is released. Is there a method available ...

Struggling to access YouTube account via Google sign-in using Puppeteer framework

I am facing an issue with my puppeteer code where I am unable to proceed past the email page after clicking next due to some bot protection by Google advising me to "Try using a different browser...etc". Is there a way to bypass this using puppeteer? I h ...

Having trouble sending messages on the server?

Programmer Seeking Help with Adding Data on the Server using JavaScript Stack I am encountering an issue with my javascript code as I am attempting to use the post method to add data on the server-side, but it seems to not be posting successfully. Can ...

Storing Firebase credentials securely in Vue.js applications after deployment with environment variables (env_var)

I've been attempting to deploy my firebase&vue application, but I've encountered issues with adding firebase credentials to the environment variables. Here's the structure within vue.js: config ---- key.js ---- keys_dev.js ---- key ...

The YQL Query is currently not returning any results

Can someone provide the YQL Query for extracting movie data from the IMDB website? I am specifically looking to retrieve cast information from the title page, using the input URL provided. Example: Input URL : ...

The combination of Array map and reduce results in an unexpected undefined output

I have a pair of arrays known as headersMap and selected_arr structured in the following manner: headersMap: [ { text: "#", align: "center", sortable: true, value: "id", align: "start&quo ...

Encountering a hydration issue in Next.js 13 due to applying initial framer-motion animation value conditionally depending on the screen size

In my Next.js 13 app, I am utilizing framer-motion for animations on a single-page layout with multiple screens. Navigation is achieved by scrolling to their respective section IDs, and I am using the traditional pages directory. One of the screens featur ...

Formatting numbers in JavaScript objects

I am looking to iterate through an array of objects and convert the string values into numbers. Here is a sample scenario: I have data in a format similar to the variable provided below. When passing this array to a kendo chart, it seems to have trouble r ...

Are strings in an array being truncated by Firebug console log?

I have a unique function for logging messages to the firebug console that I'd like to share: // Just having fun with names here function ninjaConsoleLog() { var slicer = Array.prototype.slice; var args = slicer.call(arguments); console.lo ...

Exploring the power of AngularJS with JSON datasets

While working on angularJS, I encountered a problem with calculating operations on JSON data. I need assistance in solving this issue. enter code hereCode snippet. In the "script.js" file, there is JSON data named "marksArray". My task is to calculate the ...