0

I have got an array of days:

let days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ]

Obviously the keys above are from 0 - 6. I use these days to generate a list, a user can then selecte and deselect days from this list. So if they deselect Monday and then select Sunday I now have a selected array:

let selected = [ 'sunday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ]

I then want to format the selected dates and display it to the user, but of course using the code below I will get Sunday - Saturday, when really I want Tuesday - Sunday.

let dayOne = this.selected[0];
let dayTwo = this.selected[this.selected.length - 1];

if (dayOne === undefined && dayTwo === undefined) return;

return dayOne.charAt(0).toUpperCase() + dayOne.slice(1) + ' - ' + dayTwo.charAt(0).toUpperCase() + dayTwo.slice(1);

What's a nice and clear way to do this?

Mohan Rajput
  • 634
  • 9
  • 21
Martyn Ball
  • 4,679
  • 8
  • 56
  • 126

2 Answers2

1

My recommendation:

Use a simple integer list [0...6] and use that instead. I'm pretty sure you have 7 checkboxes holding the weekday names as values. Use the numbers as values instead.

Then, when you need the array with day names, do this:

const weekdays = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ];
let selected = [5,2,4,1]; //unsorted array
selected.sort(); //careful here
let selecteddays = selected.map(d => weekdays[d]);
console.log(selecteddays);

This sort() can be problematic, gotta be careful with it. Check this on how to properly sort numeric arrays: How to sort an array of integers correctly

Phiter
  • 14,570
  • 14
  • 50
  • 84
  • Should be careful using `sort()` on number array without a numeric sort callback. It works here because range is very small but if it went 1-20 would not work – charlietfl Nov 12 '18 at 12:10
1

You can sort by comparing the index in original days array

let days = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ]
let selected = ['saturday', 'friday', 'wednesday']

selected.sort((a,b) => days.indexOf(a) - days.indexOf(b))

console.log(selected)
charlietfl
  • 170,828
  • 13
  • 121
  • 150