ekclone
ekclone

Reputation: 1092

Slice from beginning if array ended javascript

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"]

Upvotes: 3

Views: 1067

Answers (3)

Mark
Mark

Reputation: 92440

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))

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

You could use

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

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


console.log(selection);

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370679

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)));

Upvotes: 1

Related Questions