交换数组中的某些值并将其压入不同的索引



例如:

我有一个数组列表,它保存的值为:

let data = [
"10-45-23:45", 
"10-45-22:45",
"10-45-20:45",
"10-45-23:45",
"10-45-23:59,00:00-04:59", 
"10-45-23:59, 00:00-04:59",
"10-45:22:45"
]

所以,我要解决的是任何在索引中逗号之后的东西,即00:00-04:59需要向下推一个索引。这样,数据就可以被格式化为合适的格式。有什么动态的方法可以解决这个问题吗?

My Desired Output:

let data = [
"10-45-23:45", 
"10-45-22:45",
"10-45-20:45",
"10-45-23:45",
"10-45-23:59", 
" 00:00-04:59,10-45-23:59",
"00:00-04:59,10-45:22:45"
];

然后将数据排序到:

let data = [
"10-45-23:45", 
"10-45-22:45",
"10-45-20:45",
"10-45-23:45",
"10-45-23:59", 
"10-45-23:59,00:00-04:59",
"10-45:22:45,00:00-04:59"
];

但是,如果数据数组已经是下面提到的格式,那么我们不改变数组:

let data = [
"10-45-23:59,00:00-01:59",
"10-45:22:59,00:00-02:59",
"10-45-23:59,00:00-04:59",
"10-45:22:59,00:00-04:59",
"10-45-23:59,00:00-04:59",
"10-45:22:59,00:00-04:59",
"10-45-23:59,00:00-04:59",
"10-45:22:59,00:00-04:59"
]

您可以用逗号分隔每个值(并在其后面加上可选的空白),然后使用reduce将这些第二部分移位为下一个索引的第一部分。如果在循环结束时仍然有余数,则将其插入第一个数组值:

let data = [
"10-45-23:45", 
"10-45-22:45",
"10-45-20:45",
"10-45-23:45",
"10-45-23:59,00:00-04:58", 
"10-45-23:59, 00:00-04:59",
"10-45:22:45"
];
let result = data.map(s => s.split(/,s*/));
// Only change something when there is an item that does not have doubly entry
if (result.some(({length}) => length < 2)) { // must rotate second items
let overflow;
[result, overflow] = result.reduce(([acc, prev], parts) =>
[[...acc, [...prev, parts.shift()].join(",")], parts]
, [[], []]);
// What drops off at the end, should be inserted at the start
result[0] = [...overflow, result[0]].join(",");
}
console.log(result);

相关内容

  • 没有找到相关文章

最新更新