从字符串数组生成星期几对象

时间:2019-05-06 08:48:57

标签: javascript arrays string javascript-objects

我有一系列日期范围,例如:

["Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun", ...]

我需要创建一个大对象,该对象将每个字符串映射到包含所有相关日期的数组,如下所示:

var object = {
  'Mon-Tue': ['Mon', 'Tue'],
  'Mon-Wed': ['Mon', 'Tue', 'Wed'],
}

为了提供帮助,我列出了一些可能的日子:

var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

可以不用手动完成所有操作吗?

谢谢!

5 个答案:

答案 0 :(得分:3)

您可以使用Map来获取带有索引的日期,然后进行迭代直到整天。

var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    daysMap = new Map(days.map((d, i) => [d, i])),
    data = ["Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun"],
    result = Object.assign({}, ...data.map(d => {
        var [start, end] = d.split('-'),
            temp = [],
            s = daysMap.get(start),
            e = daysMap.get(end);

        while (s !== e) {
            temp.push(days[s]);
            s++;
            s %= days.length
        }
        temp.push(days[s]);
        return { [d]: temp };
    }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

如果愿意,您可以在需要的日子里花Generator

function* getDays(from, to) {
    var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        i = days.indexOf(from);

    while (days[i % days.length] !== to) yield days[i++ % days.length];
    yield days[i % days.length];
}

var data = ["Fri-Tue", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun"],
    result = Object.assign({}, ...data.map(d => ({ [d]: [...getDays(...d.split('-'))] })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

另一种使用明日对象的方法,它给出了明天。

function* getDays(from, to) {
    var tomorrow = { Sun: 'Mon', Mon: 'Tue', Tue: 'Wed', Wed: 'Thu', Thu: 'Fri', Fri: 'Sat', Sat: 'Sun' };

    yield from;
    while (from !== to) yield from = tomorrow[from];
}

var data = ["Fri-Tue", "Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun"],
    result = Object.assign({}, ...data.map(d => ({ [d]: [...getDays(...d.split('-'))] })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:2)

您可以创建一个days数组。首先,split范围并获取当前范围的索引。

  • 如果为toIndex > fromIndex,请使用slice获取数组的一部分。

  • 如果fromIndex > toIndex

    • 获取从fromIndexdays数组末尾的数组
    • 加上,从0到toIndex

const array = ["Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun"]

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

const output = {}

array.forEach(range => {
  const [fromIndex, toIndex] = range.split('-').map(a => days.indexOf(a))
  
  if(fromIndex > toIndex)
    output[range] = [...days.slice(fromIndex), ...days.slice(0, toIndex + 1)]
  else
    output[range] = days.slice(fromIndex, toIndex + 1)
})

console.log(output)
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:1)

您可以按照以下步骤进行操作:

  • 应用reduce()包含范围的字符串数组,并将累加器设置为空对象{}
  • 然后用split()-字符串。
  • 每天在indexOf()数组中获取days
  • 然后在slice()上使用days,分别为其提供字符串的第一部分和第二部分的索引。
  • 将它们设置为新的key字符串,并将其值设置为slice()返回的数组

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

var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

let res = arr.reduce((ac,x) => {
  let temp = x.split('-').map(a => days.indexOf(a));
  ac[x] = days.slice(temp[0],temp[1]+1);
  return ac;
},{})

console.log(res)

答案 3 :(得分:0)

    let arr =  ["Mon-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun"];
    var days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    
    var result = {};

    arr.map((x) => {

      var splitedArr = x.split('-');

      //left day < right day
      if (days.indexOf(splitedArr[0]) < days.indexOf(splitedArr[1]) + 1){
        var slicedDays = days.slice(days.indexOf(splitedArr[0]),days.indexOf(splitedArr[1]) + 1);
      }
      else{//left day > right day
        var slicedDays = days.slice(days.indexOf(splitedArr[0]),days.length);
        slicedDays = slicedDays.concat(days.slice(0,days.indexOf(splitedArr[1]) + 1));
      }

      result[x] = slicedDays;

    });
    
    console.log(result);

答案 4 :(得分:0)

最简单的方法是创建一个重复数天的数组。

let input = ["Fri-Tue", "Mon-Wed", "Mon-Thu", "Mon-Fri", "Mon-Sat", "Mon-Sun", "Tue-Mon", "Tue-Wed", "Tue-Thu", "Tue-Fri", "Tue-Sat", "Tue-Sun"];
let days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
let daysArr = [...days, ...days];

let out = {};

input.forEach((e) => {
	if(!out[e]) {
		out[e] = getDays(e);
	}
});

function getDays(str) {
	let [from, to] = str.split('-').map(e => days.indexOf(e));
	to = from < to ? to : to+7
	return daysArr.slice(from, to+1);
}

console.log(out)