Starting a checkbox group with values based on total number

I am facing a challenge with a group of checkboxes that have values assigned as 1,2,4,8,16,32,64. Each number corresponds to a day of the week (e.g. Sunday, Monday etc...)

The total value of the checkbox group is calculated as the sum of the selected checkboxes. For example, Sun, Mon, Tue = 7.

Despite my efforts, I have not been successful in creating a function that can break down the total sum into the relevant numbers to ensure the correct checkboxes are selected when editing.

(Unfortunately, I am unable to change the values of the checkboxes to strings as it was configured this way by the back-end team)

Initial Attempt

`initSpecificDays(){
    let specificDaysArr = [1,2,4,8,16,32,64];
    let daysTotal = 44;
    let selectedDays = specificDaysArr.map(num=>{
      return daysTotal / num;
    })
    console.log(selectedDays)
  }`

Answer №1

To determine the correct day, you can verify the given value by using the bitwise AND operator with a calculated value of one and the index using the left shift operator.

If the result is true, then you have found the corresponding day.

This method involves examining each bit and comparing it accordingly.

For example, with the value of 7 representing ["Sun", "Mon", "Tue"]

index  left shift  decimal   binary   bitwise AND   decimal   binary  comment
-----  ----------  -------  -------  ------------  -------  -------  -------
   0     1 << 0         1         1   7 &  1        1         1  take
   1     1 << 1         2        10   7 &  2        2        10  take
   2     1 << 2         4       100   7 &  4        4       100  take
   3     1 << 3         8      1000   7 &  8        0         0
   4     1 << 4        16     10000   7 & 16        0         0
   5     1 << 5        32    100000   7 & 32        0         0
   6     1 << 6        64   1000000   7 & 64        0         0

const
    getDays = value => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
        .filter((_, i) => value & 1 << i);

console.log(getDays(7));  // ["Sun", "Mon", "Tue"]
console.log(getDays(65)); // ["Sun", "Sat"]

Answer №2

Here is an alternate rendition of Nina's explanation, enhanced with additional visuals to facilitate comprehension of the concepts at the bit level.

Essential Knowledge

Before diving into the subject matter, it's crucial to understand that JavaScript can manipulate bits using the 0b prefix. Familiarity with bitwise operators like "and" (&) and "shift right" (>>) is also advantageous:

> | 0b1
< | 1
> | 0b111
< | 7
> | (7).toString(2)
< | "111"
> | 1 & 1
< | 1
> | 1 & 0
< | 0
> | (0b101 & 0b110).toString(2)
< | "100"
> | (0b100 >> 1).toString(2)
< | "10"
> | (0b100 >> 2).toString(2)
< | "1"
> | (0b100 >> 3).toString(2)
< | "0"

In the equation L & R, L is commonly known as the "bit map," while R is referred to as the "bit mask." The bit map comprises binary flags (0/1, off/on, false/true), while the bit mask acts as a selector:

  flags  |   0000111 |   0000111 |   0000111
& mask   | & 0000001 | & 0000011 | & 0100100
= subset | = 0000001 | = 0000011 | = 0000100

In a binary number, the rightmost bit (bit 0) is termed the "least significant bit" (LSB), whereas the leftmost bit is the "most significant bit" (MSB):

> | 0b0000111 >> 0 & 1 // reads bit 0 (LSB)
< | 1
> | 0b0000111 >> 6 & 1 // reads bit 6 (MSB)
< | 0

Data Representation

Representation of days:

  SFTWTMS <---- pay attention
0b0000001 =  1 = Sunday
0b0000010 =  2 = Monday
0b0000100 =  4 = Tuesday
0b0001000 =  8 = Wednesday
0b0010000 = 16 = Thursday
0b0100000 = 32 = Friday
0b1000000 = 64 = Saturday

Bit map indicating the selected days:

    |     SFTWTMS |
  1 |   0b0000001 |   Sunday
+ 2 | + 0b0000010 | + Monday
+ 4 | + 0b0000100 | + Tuesday
= 7 | = 0b0000111 | = selection

Visualization of the selected days' bit map, with explanatory notes:

Sat 0 drop (bit 6) <---- MSB
Fri 0 drop (bit 5)
Thu 0 drop (bit 4)
Wed 0 drop (bit 3)
Tue 1 take (bit 2)
Mon 1 take (bit 1)
Sun 1 take (bit 0) <---- LSB

Selection Process

This process entails reading the bit map from LSB to MSB:

for i in [0-6] do: take ith day if bitmap >> i & 1 equals 1

Step-by-step illustration:

                   SFTWTMS |   S
0b0000111 >> 0 = 0b0000111 |   1
               & 0b0000001 | & 1
               = 0b0000001 | = 1 (take "Sun")
                         ^ |
                    SFTWTM |   M
0b0000111 >> 1 = 0b0000011 |   1
               & 0b0000001 | & 1
               = 0b0000001 | = 1 (take "Mon")
                         ^

Example

Practical demonstration:

> | Sun = 0b0000001
< | 1
> | Mon = 0b0000010
< | 2
> | Tue = 0b0000100
< | 4
> | bitmap = Sun + Mon + Tue
< | 7
> | days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
< | ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
> | days.filter((_, i) => bitmap >> i & 1)
< | ["Sun", "Mon", "Tue"]

Note that the bit map can be interpreted as an array of booleans:

> | take = [true, true, true, false, false, false, false]
< | [true, true, true, false, false, false, false]
> | selection = []
< | []
> | for (i = 0; i < days.length; i++) {
  |   if (take[i]) selection.push(days[i]);
  | }
  | selection
< | ["Sun", "Mon", "Tue"]

Moreover, bitmap >> i & 1 ("retrieve the ith bit") is equivalent to take[i] ("access the ith element"):

> | for (i = 0; i < 7; i++) {
  |   console.log(i, bitmap >> i & 1, take[i]);
  | }
  | 0 1 true
  | 1 1 true
  | 2 1 true
  | 3 0 false
  | ...

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

Tips for showcasing several images with accompanying content once the webpage has finished loading

I am faced with an issue on my PHP website. The website is a social networking platform with numerous images and contents. I am seeking a way to first display only the content to the user, then show the images after they have all finished loading. Addition ...

Guide to attaching a click event in a subview of Backbone

I'm struggling with understanding event binding in a Backbone subview. Here's how my view is set up: TenantView = Backbone.View.extend({ events: { "click": "setActive" }, initialize: function() { this.parentEl = this.options.parent ...

Having issues with the NX CLI command in my Angular workspace, it is not functioning as expected

Currently, I am in the process of setting up an nx workspace with Angular. Everything seems to be in order as I have installed nx globally. However, whenever I try to launch the nx dep-graph command, a window pops up asking how I would like to open it. Ev ...

The functionality of Styles in Material UI seems to be malfunctioning

I'm currently learning how to use Material UI for React, specifically focusing on makeStyles. Below is the JavaScript code I have: import React from "react"; import MenuIcon from "@material-ui/icons/Menu"; import EventNoteIcon fr ...

Issue with passing a dynamic array in the write system call in C++

I have utilized the fork function to create two processes. My goal is to transmit an integer array stored in heap memory to the child process using write and read system calls. While the problem is resolved when the array resides on the stack in the parent ...

What is the best way to deliver flash messages using Express 4.0?

Currently, my web application requires authentication, and I am encountering an issue with the signup page. If a user tries to sign up with an email that is already in the database, I want to display an error message. Here is the code snippet I am using on ...

Could you assist me in navigating the process of creating a dynamic 10x10 multiplication table using HTML and JavaScript? I'm eager to learn where to begin with this methodology

As I explore various questions related to the "simple" multiplication tables, I find myself with a more fundamental query. I am seeking clarity on how Javascript operates when intertwined with HTML, as that is where my confusion lies. In my multiplication ...

The concept of RxJS's catchError function involves the return of a versatile

It's interesting that catchError is returning an Observable union type as Observable<{} | Page} instead of just Observable<Page>. The error message from the compiler reads: Type 'Observable<{} | Page>' is not assignable to t ...

Launching PDF on IE11 in a new tab seamlessly without any prompts - mssaveoropenblob

We are in the process of transitioning an ASP.NET MVC application that used to have the functionality of opening a PDF file in a new tab using FileContentResult. return new FileContentResult(byteArray, "application/pdf"); As part of this migration to Rea ...

Mobile website includes a share button that activates share dialogs for iOS and Android systems

Can a share button be created on my website that will trigger share dialogs on iOS and Android devices? Specifically, I am referring to the dialogs shown below for each system: https://i.sstatic.net/dw759.jpg https://i.sstatic.net/NS8W3.png I am lookin ...

An error arises during the process of summing array elements with a "for loop"

Here is some code I am working on: String array[]=new String[5]; for(int i=0;i<array.length;i++){ array[i]= "item "+String.valueOf(i); i++; } After my application crashed, I received the following log message: java.lang.IndexO ...

The call stack size has reached its maximum limit;

Encountering an issue with the use of componentDidMount(). This method is intended to display a Tooltip by utilizing the function _getContentTooltip(). However, the problem arises as it triggers the error message common.js:444 RangeError: Maximum call st ...

What is the best way to create 7 or 8 column grids with Vuetify's v-row and v-col components?

I understand that vuetify's grid system is based on a 12-column flex-box layout, but I would like to customize it to have 7 or 8 columns by default instead of the usual 12. In the code snippet below, you can see my attempt: <v-row> <v-col ...

Unable to properly utilize environment variables on Vercel when using Nuxt framework

I'm encountering difficulties accessing my environment variables on Vercel. When I test the site on my localhost, everything works fine; however, once it's deployed to Vercel, the access to environment variables in my components and plugins direc ...

Utilizing the power of jQuery within three.js

Thank you once again for your previous assistance, but I find myself in need of your expertise once more. I have successfully added markers to my map as desired. However, these markers now require functionality to be clickable. Specifically, when clicked, ...

Python function for updating an existing ndarray

In my function, there is a loop that looks like this: mu=np.zeros((T,p)) mu_post=np.zeros((T,p)) for t in arange(T): mu_post[t]= np.dot(a,b) mu[t+1]= mu_post[t] some other processing As the loop approaches the end (t=T-1), the code exi ...

Move values to the right while filling in any empty spaces with zeros

I need help repositioning the values in a list to shift them right by one position and fill index 0 with a value of 0. For example: a = [8,9,10,11] output = [0,8,9,10] I attempted using the following code: a.insert(0,a.pop()) This code shifted the elem ...

Adjust the size of the textarea to accommodate the number of lines of text

<script type="text/javascript"> function AutoGrowTextArea(textField) { if (textField.clientHeight < textField.scrollHeight) { textField.style.height = textField.scrollHeight + "px"; if (textField.clientHeight ...

Managing numerous range sliders in a Django form

My Request: I am looking to have multiple Range sliders (the number will change based on user selections) on a single page. When the sliders are moved, I want the value to be updated and displayed in a span element, as well as updating the model. The Issu ...

Acquire information from an Angular service and output it to the console

I am having trouble logging data from my service file in the app.component file. It keeps showing up as undefined. Below is the code snippet: service.ts getBillingCycles() { return this.http.get('../../assets/download_1.json'); }; app.com ...