javascript 如何通过设置一周的第一天来排序一周的天数?

bkkx9g8r  于 2023-04-10  发布在  Java
关注(0)|答案(7)|浏览(192)

如何排序?例如,我希望我一周的第一天是星期一。从这个:


我想要这个:

周一周二周三周四周五周六周日

或者我希望我一周的第一天是星期五
那么输出应该是这样的:

酒店周五周六周日周一周二周三周四

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by default first day of week is 0
let firstDayOfWeek = 1 //Mon

days = days.map(m=>{
  //how i can sort this?
  return m
})
8yparm6h

8yparm6h1#

firstDayOfWeek之前的天数切片,并将它们添加到数组的末尾:

const orderByFirstDayOfWeek = (firstDayOfWeek, days) =>
  [...days.slice(firstDayOfWeek), ...days.slice(0, firstDayOfWeek)]

const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by default first day of week is 0

console.log(JSON.stringify(orderByFirstDayOfWeek(1, days))) // Mon 1st
console.log(JSON.stringify(orderByFirstDayOfWeek(5, days))) // Fri 1st
bwntbbo3

bwntbbo32#

您可以按以下方式对天数进行排序

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by default first day of week is 0
let firstDayOfWeek = 2 //Mon

let sorted = days.map((_, i) => days[(i+firstDayOfWeek)%7]);

console.log(sorted)
83qze16e

83qze16e3#

您可以创建一个具有days数组的2次迭代的数组,然后使用slice从任何索引中获取7个项

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

function getSortedWeek(firstDayOfWeek, days) {
  return [...days, ...days].slice(firstDayOfWeek, firstDayOfWeek + 7)
}

console.log(getSortedWeek(1, days)) // Mon
console.log(getSortedWeek(3, days)) // Wed

代码[...days, ...days]给出了一个有14个元素的数组,可以在一周中的任何一天工作。

ee7vknir

ee7vknir4#

你可以取一个天数,通过添加delta来调整值,然后用7来排序。

const
    dayValues = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 },
    days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    firstDayOfWeek = 1,
    delta = 7 - firstDayOfWeek;

days.sort((a, b) => (dayValues[a] + delta) % 7 - (dayValues[b] + delta) % 7);

console.log(days);
vuktfyat

vuktfyat5#

这样试试

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by 
function sortDay(firstDayOfWeek){
  var result = [];
  for(i=0; i<days.length;i++){
    result.push(days[firstDayOfWeek%7])
    firstDayOfWeek++;
  }
  console.log(JSON.stringify(result))
}
sortDay(1)
sortDay(4)
lawou6xi

lawou6xi6#

let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] //by default first day of week is 0
let firstDayOfWeek = 2 //Mon

days = days.slice(firstDayOfWeek).concat(days.slice(0, firstDayOfWeek));

console.log(days);
zfciruhq

zfciruhq7#

我做如下。

const daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
const firstDayOfWeek = 'Sunday';

daysOfWeek.sort(function(a, b) {
  const aIndex = daysOfWeek.indexOf(a);
  const bIndex = daysOfWeek.indexOf(b);
  
  if (aIndex < daysOfWeek.indexOf(firstDayOfWeek)) {
    aIndex += daysOfWeek.length;
  }
  
  if (bIndex < daysOfWeek.indexOf(firstDayOfWeek)) {
    bIndex += daysOfWeek.length;
  }
  
  return aIndex - bIndex;
});

console.log(daysOfWeek);
// output: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

相关问题