简体   繁体   English

根据当前日期排序数组

[英]Ordering an array based on current date

I am trying to re-order the array below given todays date: 我想在今天的日期下重新排序下面的数组:

[
    {
        "index": "0",
        "day": "Monday",
        "food": "Salad"
    },
    {
        "index": "1",
        "day": "Friday",
        "food": "Pasta"
    },
    {
        "index": "2",
        "day": "Sunday",
        "food": "Pasta"
    },
    {
        "index": "3",
        "day": "Thursday",
        "food": "Pasta"
    },
    {
        "index": "4",
        "day": "Tuesday",
        "food": "Pasta"
    },
    {
        "index": "2",
        "day": "Sunday",
        "food": "Pasta"
    },
    {
        "index": "5",
        "day": "Wednesday",
        "food": "Pasta"
    },
    {
        "index": "6",
        "day": "Saturday",
        "food": "Pasta"
    }
]

Say today is Saturday , after ordering, the expected output by item index is: 6, 2, 2, 0, 4, 5, 3, 1 If today was Tuesday , the output by index is: 4, 5, 3, 1, 6, 2, 2, 0 说今天是Saturday ,在订购之后,按项目索引的预期输出是:6,2,2,0,4,5,3,1如果今天是Tuesday ,则索引的输出是:4,5,3,1, 6,2,2,0

I am using moment.js , and so far I am failing to create a non bulky code for this. 我正在使用moment.js ,到目前为止,我没有为此创建一个非庞大的代码。 Eventually I would like to wrap the code in a custom orderBy filter to be used on a ng-repeat directive. 最后,我想将代码包装在自定义orderBy过滤器中,以便在ng-repeat指令中使用。

Here's the minimal solution I came up with: 这是我提出的最小解决方案:

const DAYS = { 'Sunday': 0, 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6 };

// Get the relative index of a day using today as a reference.
function relativeIndex(day) {
  const TODAY = new Date().getDay();
  return (DAYS[day] - TODAY + 7) % 7;
}

// Sort a lit of data starting by today.
function sort(data) {
  return data.sort((a, b) => relativeIndex(a.day) - relativeIndex(b.day));
}

The key here is the relativeIndex function which calculates the index of any day using today as a reference. 这里的关键是relativeIndex函数,它使用今天作为参考来计算任何一天的索引。

Sorting by today was a little tricky to achieve just using sort. 今天排序对于实现仅使用排序来说有点棘手。 To overcome it we are creating an array of days, then resorting that so the current day is at index 0, then sorting your calendar array based on the sorted days. 为了克服这个问题,我们创建了一个天数,然后求助于当前日期为索引0,然后根据排序的天数对日历数组进行排序。

to avoid having to calculate the sortedDays multiple times, it's wrapped in a closure that returns the function that will sort the given array. 为了避免多次计算sortedDays ,它被包装在一个闭包中,该闭包返回将给定数组排序的函数。

It's immutable so you won't need to change the original order if you don't need to. 它是不可变的,因此如果您不需要,您将不需要更改原始订单。

 const calendar=[{index:"0",day:"Monday",food:"Salad"},{index:"1",day:"Friday",food:"Pasta"},{index:"2",day:"Sunday",food:"Pasta"},{index:"3",day:"Thursday",food:"Pasta"},{index:"4",day:"Tuesday",food:"Pasta"},{index:"2",day:"Sunday",food:"Pasta"},{index:"5",day:"Wednesday",food:"Pasta"},{index:"6",day:"Saturday",food:"Pasta"}]; const sortByToday = (function() { const date = new Date() const today = date.getDay() const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] const sortedDays = [ ...days.slice(today), ...days.slice(0, today) ] return function(calendar) { return calendar.slice().sort((a, b) => { return sortedDays.indexOf(a.day) > sortedDays.indexOf(b.day) }) } })() console.log( sortByToday(calendar) ) 

Given 'menu' as given array, use customized comparison to sort: 将'menu'作为给定数组,使用自定义比较进行排序:

var map = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var day = (new Date()).getDay();
menu.sort(function(a, b){
    var aDay = map.indexOf(a.day), bDay = map.indexOf(b.day);
    return (aDay - bDay) * 
        (day <= Math.min(aDay, bDay) || day > Math.max(aDay, bDay) ? 1 : -1);
});

for(var i=0; i<menu.length; ++i){
  console.log(menu[i].index);
}

Using Date() gymnastics. 使用Date()体操。 Scroll down to see commented code. 向下滚动以查看已注释的代码。

 let arr = [ { "index": "0", "day": "Monday", "food": "Salad" }, { "index": "1", "day": "Friday", "food": "Pasta" }, { "index": "2", "day": "Sunday", "food": "Pasta" }, { "index": "3", "day": "Thursday", "food": "Pasta" }, { "index": "4", "day": "Tuesday", "food": "Pasta" }, { "index": "2", "day": "Sunday", "food": "Pasta" }, { "index": "5", "day": "Wednesday", "food": "Pasta" }, { "index": "6", "day": "Saturday", "food": "Pasta" } ] // first create an array to label days let dayOfWeekLabels = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; let days = []; let runningDate = new Date(); // optional offset for debugging / testing //runningDate.setDate( runningDate.getDate()+1 ); // now create an array that rearranges the first array // according to what day it is today dayOfWeekLabels.forEach((label,i) => { days.push( dayOfWeekLabels[new Date(runningDate).getDay()] ); runningDate.setDate( runningDate.getDate()+1 ); }); // now enhance the original array with an "order" value let orderedArr = arr.map(obj => { obj.order = days.indexOf(obj.day); return obj; }); // now sort based on the "order" value orderedArr.sort((a,b) => { return (a.order - b.order); }); /* console.log(orderedArr); */ document.getElementById('output').innerHTML = JSON.stringify(orderedArr,null," "); 
 <pre><code class="json" id="output"></code></pre> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM