[英]How do I get max 8 dates from an array of dates with the same interval between their indexes without repeating month?
For exemplo, in this array, I want to return max 8 elements without repeating month.例如,在这个数组中,我想返回最多 8 个元素而不重复月份。 Include the first element is optional.包含第一个元素是可选的。
['01-15', '01-16', '01-17', '01-18', '01-19', '01-20', '01-21', '01-22', '01-23', '01-24', '01-25', '01-26', '01-27', '01-28', '01-29', '01-30', '02-01', '01-02', '02-03', '02-04', '02-05', '02-06', '02-07', '02-08', '02-09', '02-10', '02-11', '02-12', '02-13', '02-14', '02-15', '02-16', '02-17', '02-18', '02-19', '02-20', '02-21', '02-22', '02-23', '02-24', '02-25', '02-26', '02-27', '02-28', '03-01', '03-02', '03-03', '03-04', '03-05', '03-06', '03-07', '03-08', '03-09', '03-10', '03-11', '03-12', '03-13', '03-14', '03-15']
would return会回来
['01-15', '02-05', '03-01']
If by chance the array has a range of 12 months, this would return, for exemplo (I don't know the exactly result):如果碰巧数组的范围是 12 个月,这将返回,例如(我不知道确切的结果):
['01-20', '03-30', '05-01', '06-10', '07-20', '09-01', '11-01', '12-31'] // array size must be 8 and ensure that the months do not repeat
My code is:我的代码是:
const newArray = oldArray
.filter(function(date, index, arr){
const delta = Math.floor(oldArray.length / 8);
return index % delta === delta - 1; // would be something here
});
This returns max 8 non-repeating months as you describe, but it doesn't output "02-05" but "02-01" as 2nd element.如您所述,这最多返回 8 个非重复月份,但它不是 output“02-05”,而是“02-01”作为第二个元素。 If that should be the case then extra criteria should be added to the description.如果是这种情况,则应在描述中添加额外的标准。
function filterEightMonths(array) {
const map = {};
let mapSize = 0;
for (const date of array) {
const [month, day] = date.split('-');
if (!map[month]) {
map[month] = date;
mapSize++;
}
if (mapSize > 8) {
break;
}
}
return Object.values(map);
}
You could do something like this你可以这样做
function filterDateList(list) {
const result = list.reduce((previousValue, currentValue) => {
if (
!previousValue.find(
(el) => el.split("-")[0] === currentValue.split("-")[0]
)
) {
previousValue.push(currentValue);
}
return previousValue;
}, []);
return result.slice(0, 8);
}
const dates = ['01-15', '01-16', '01-17', '01-18', '01-19', '01-20', '01-21', '01-22', '01-23', '01-24', '01-25', '01-26', '01-27', '01-28', '01-29', '01-30', '02-01', '01-02', '02-03', '02-04', '02-05', '02-06', '02-07', '02-08', '02-09', '02-10', '02-11', '02-12', '02-13', '02-14', '02-15', '02-16', '02-17', '02-18', '02-19', '02-20', '02-21', '02-22', '02-23', '02-24', '02-25', '02-26', '02-27', '02-28', '03-01', '03-02', '03-03', '03-04', '03-05', '03-06', '03-07', '03-08', '03-09', '03-10', '03-11', '03-12', '03-13', '03-14', '03-15'];
console.log(filterDateList(dates));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.