Generating a string indicating the range of days chosen

Imagine a scenario where there is a selection of days available to the user (they can choose multiple).

The list includes Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, each with an associated number from 0 to 6. For instance, Sunday corresponds to 0 and Saturday to 6:

vm.weekDays = [
    {name: 'Sunday', number: 0},
    {name: 'Monday', number: 1},
    {name: 'Tuesday', number: 2},
    {name: 'Wednesday', number: 3},
    {name: 'Thursday', number: 4},
    {name: 'Friday', number: 5},
    {name: 'Saturday', number: 6},
]

If the user selects Sunday, Monday, and Tuesday, the output should be "Sunday - Tuesday". However, if they select Sunday, Monday, Tuesday, and Thursday, it should display as "Sunday - Tuesday, Thursday". Finally, choosing Sunday, Tuesday, and Thursday should show exactly those selected days.

To store these selections and display them accordingly, I am saving the strings in an array. Here is what I have implemented so far:

function test() {

    vm.display = [];

    var sortedWeekdays = _.sortBy(vm.sWeekDays, 'number');

    var start = 0;
    var end = 0;

    if(sortedWeekdays.length > 1){
        for(var i=0; i <= sortedWeekdays.length-2; i++){
            if(sortedWeekdays[i].number + 1 != sortedWeekdays[i+1].number) {
                start = i + 1;
                end = i;
                vm.display.push(sortedWeekdays[i].name);
            }
            end = i + 1;
        }

        vm.display.push(sortedWeekdays[start].name + " - " + sortedWeekdays[end].name);
    } else {
        vm.display.push(sortedWeekdays[0].name);
    }
}

Currently, the function successfully displays consecutive days, but selecting Sunday through Tuesday and Thursday does not yield the desired outcome.

If you have any suggestions or solutions, your assistance would be highly appreciated.

Answer №1

I made some adjustments to your code and I believe the solution is now easy to understand. Here is my revised implementation

 var vm = {};
 vm.weekDays = [{
     name: 'Sunday',
     number: 0
 }, {
     name: 'Monday',
     number: 1
 }, {
     name: 'Tuesday',
     number: 2
 }, {
     name: 'Wednesday',
     number: 3
 }, {
     name: 'Thursday',
     number: 4
 }, {
     name: 'Friday',
     number: 5
 }, {
     name: 'Saturday',
     number: 6
 }, ]

 function formatSelected(selected) {
     vm.display = [];
     selected = _.sortBy(selected, 'number'); //this could be vm.selected instead of passing it as a parameter

     var lastnumber = 0,
         template = {
             name: '',
             number: 0
         },
         last,
         list = [];

     if (selected.length > 0) {
        last = selected[0];
        for (var i = 0; i < selected.length; i++) {
            if (last) {
                var left = selected[i - 1] ? selected[i - 1] : angular.copy(template);
                console.log(selected[i].number - left.number)

                if (i > 0 && selected[i].number - left.number > 1) {
                    list.push(((left.name != last.name) ? (last.name + '-') : '') + left.name);
                    last = selected[i];
                }
                if((i == (selected.length - 1))) {
                    list.push(((selected[i].name != last.name) ? (last.name + '-') : '') + selected[i].name);
                }
            } else {
                last = selected[i];
            }
        }
    }

     vm.display = list;
 };

You can use the function by passing an array as shown below:

 formatSelected([{
     name: 'Sunday',
     number: 0
 }, {
     name: 'Monday',
     number: 1
 }, {
     name: 'Tuesday',
     number: 2
 }, {
     name: 'Wednesday',
     number: 3
 }, {
     name: 'Saturday',
     number: 6
 }, ]);

I have also updated the function to handle arrays like this:

formatSelected([{ name: 'Sunday', number: 0}, { name: 'Tuesday', number: 2}, { name: 'Thursday', number: 4}]);

Answer №2

One way to tackle this problem is by using a map to store the range, and then parsing the map to create the resulting string.

// Here is an example of the map structure 
[
    [{
        name: 'Sun',
        number: 0
    }, {
        name: 'Mon',
        number: 1
    }, {
        name: 'Tue',
        number: 2
    }],
    [{
        name: 'Thu',
        number: 4
    }]
]

Next step involves checking each range to determine if it should be converted to 'day1 - day3' or 'day1, day2'.

For a live example, you can visit this JSFiddle link

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

After being redrawn, the line on the canvas vanishes

After updating the angle value, the line is quickly redrawn correctly but then disappears. It seems like the input value may be getting refreshed and set to undefined again. How can I ensure that the line retains the correct angle? <script language=" ...

What methods can users employ to effectively manage and maintain their in-app purchases using my application?

Hey there, I could really use some assistance. Recently, I created a mobile app for a client that allows users to purchase and watch video courses. However, I'm facing an issue where when a user buys a course and then refreshes the app, they are redir ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

To achieve the desired format, where should I press or manipulate the information?

I need help with manipulating arrays to generate a specific JSON file structure. I've made some progress but got stuck at this point: var T_nn_IN = document.getElementById('datatablenewname'); var tabledata_newname_initialname = []; ...

Unable to launch the Express application on a 64-bit Windows 7 operating system

After successfully installing Node for Windows/64bit and being able to run the server with an example from the Node homepage, I encountered an issue when setting up an Express app. Despite installing Express using the command npm install -g express and r ...

'view' is not recognized as a valid property of the 'div' element in Ionic3, so it cannot be bound

I am a beginner with Ionic and I'm trying to incorporate Angular Calendar into my Ionic3 application. However, I am encountering an error that says, "Can't bind to 'view' since it isn't a known property of 'div'. Here&ap ...

Retrieve information from an array of objects by utilizing a separate array

There are two separate arrays provided below: ages = [20,40,60]; doctors = [{ "name": "Moruu", "age": 18, "sex": "Male", "region": "Africa" }, { "name": "Khol ...

Using Jquery's getJson method, we can easily fetch and retrieve the appropriate JSON string by

I have the following code snippet at the beginning of the JSON url: if(isset($_GET['template']) && $_GET['template']=="blue") { $inifile_path="ctr/subthemes/blue/"; } else { $inifile_path="ctr/subthemes/fresh-n-clean/"; } Addi ...

Unable to locate image in React framework

When attempting to display an image, I encountered a 404 error even though the folder containing it is being served properly. Code snippet from JSX file: render: function(){ ... return <button type="button" id="powerButton" onClick={this.someFun}>& ...

Exploring the Power of Constants in Karma and Jasmine for Enhanced Performance

To sum it up: I prefer storing hard-coded values in a separate file for reuse across multiple test specifications. Explaining further: Currently following the AngularJS tutorial, I am aiming to write more organized code. In step 5, they mention using hard ...

How to use the route.navigate() method in Angular 9 to open a URL in a new tab with a query string

When a button is clicked within a table in our application, I have to open a new tab with details of a specific record from the table. Currently, the code I am using navigates to a new URL and uses resolvers to fetch data from the backend on the new page. ...

The initial component update

I am new to React and currently working on a main component that includes a child component with a table. Upon mounting, I make an API request to fetch data which is then displayed in the table. My issue arises when, after the initial update of the child c ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

The redirection from Azure AD SSO is not working properly following a logout

In my quest to integrate Azure AD login into a single-page application built with ReactJS, I utilized the MSAL React package. While successfully implementing the login functionality, I encountered an issue during logout where I found myself unable to redir ...

Submitting a Complex JSON Object through a URL with Javascript

I am attempting to send a complex JSON Object in a URL input = { "id": 1, "sd": "123", "filter": { "h": 1,"road": true }, "legs": [{ "id": 1, "x1": -0.001, "y1": 51.122 }, { "id": 2, "x1": -12, "y1": 12 }] }; I have experimented with these methods data ...

Angular - Implement $sanitize for all user inputs

When it comes to my server side, I make sure to sanitize everything that comes in. For my Angular app client side, I've taken the same approach in certain cases, such as with contact forms. However, I'm starting to think maybe I should just appl ...

Is it possible to preserve the numerical type of a percentage when applying number formatting?

After applying number formatting, I converted a numerical value of 150 to 150.00%. Although this is the desired display format with the percentage sign included, the data type remains as string instead of number. Is there a method to convert it back to a ...

Creating visually appealing Highcharts.js visualizations for both mobile and desktop devices

Has anyone had success implementing a responsive design with Highcharts to ensure charts look great on both mobile and desktop screens? By default, Highcharts do adjust when resizing the browser window, but sometimes the X-axis can become cluttered by tic ...

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...