3

So I'm working on some filters where users can select even from ex: "Friday to Tuesday" but how to I slice these from an array of dates

var days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

So how do I slice from index from 5 to 2 which should return:

["friday", "saturday", "sunday", "monday", "tuesday"]
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
ekclone
  • 1,030
  • 2
  • 17
  • 39
  • What have you tried? Show your work so we can help you fix it. – Soviut Jul 22 '19 at 01:13
  • 1
    This shows an example of treating the array in a circular manner: https://stackoverflow.com/a/17483207/11780044 – Horatius Cocles Jul 22 '19 at 01:15
  • Possible duplicate of [How to access array in circular manner in JavaScript](https://stackoverflow.com/questions/17483149/how-to-access-array-in-circular-manner-in-javascript) – Horatius Cocles Jul 22 '19 at 01:23

3 Answers3

3

You could make a simple function that tests whether the end is smaller than the start and slice accordingly:

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

const wrapslice = (arr, start, end)  =>{
    return end < start 
    ? arr.slice(start).concat(arr.slice(0, end))
    : arr.slice(start, end)
}
console.log(wrapslice(days, 5, 2))
console.log(wrapslice(days, 2, 5))
console.log(wrapslice(days, 4))
Mark
  • 90,562
  • 7
  • 108
  • 148
2

You could use

var days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

const selection = [...days.slice(4), ...days.slice(0, 2)];


console.log(selection);
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1

Friday is at index 4, so slice from index 4, and .concat with a slice of indicies 0 to 2:

const arr = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
console.log(arr.slice(4).concat(arr.slice(0, 2)));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320