很抱歉,如果标题有点令人困惑。不知道怎么回事......
我有一系列日期:
SELECT
gender,
COUNT(*) AS total
FROM
(
SELECT gender
FROM memberOne
UNION ALL
SELECT gender
FROM memberTwo
) t
GROUP BY gender
ORDER BY gender DESC
我还有一个包含日期的json数据数组。
var dateRange = ["2017-08-21", "2017-08-22", "2017-08-23", "2017-08-24", "2017-08-25", "2017-08-26", "2017-08-27"];
所以我要做的是检查var jsonArray = [
{
date: "2017-08-21",
edit: false,
text: "some text"
},
{
date: "2017-08-23", //notice skipped 2017-08-22
edit: false,
text: "some text"
},
...
];
中每个日期的jsonArray
,以及dateRange
的任何日期是否dateRange
不存在做点什么。
我的做法是为jsonArray
中的每个日期执行indexOf
,但我意识到例如dateRange
与"2017-08-23"
相比会被触发,但我不要这样,因为"2017-08-21"
实际上存在于数组中......
这有意义吗?
感谢您的帮助!
答案 0 :(得分:2)
我不知道我是否得到了它但你想检查jsonArray
中的任何项目是否包含dateRange
中的日期吗?
您可以执行以下操作:
let yourKey = jsonArray.some((item) => {
return dateRange.contains(item.date)
})
如果任何jsonArray项目日期与dateRange日期匹配,则会将true
返回yourKey
。是吗?
[编辑]
如果你想检查每个json数组项并做一些你可以做的事情:
jsonArray.forEach((item) => {
if (dateRange.contains(item.date)) {
// The date is in the array, do something
} else {
// The date is not in the array, do something else.
}
})
答案 1 :(得分:1)
O(n ^ 2)的朴素方法是:
var jsonArray = [
{
date: "2017-08-21",
edit: false,
text: "some text"
},
{
date: "2017-08-23", //notice skipped 2017-08-22
edit: false,
text: "some text"
},
];
var dateRange = ["2017-08-21", "2017-08-22", "2017-08-23", "2017-08-24", "2017-08-25", "2017-08-26", "2017-08-27"];
for(var i = 0; i < dateRange.length; i++){
for(var j = 0; j < jsonArray.length; j++){
if(dateRange[i] == jsonArray[j].date){
console.log("Date Found:" + dateRange[i]);
}
}
}
&#13;
答案 2 :(得分:1)
它是这样的:
function DateRangeTester(startDateString, endDateString){
var start = new Date(startDateString).getTime();
var end = new Date(endDateString).getTime();
this.test = function(testDateString, passFunc, failFunc, passFuncContext, failFuncContext){
var pc = passFuncContext || this;
var fc = failFuncContext || this;
var test = new Date(testDateString).getTime();
if(test >= start && test <= end){
passFunc.call(pc, testDateString);
}
else{
failFunc.call(fc, testDateString);
}
}
}
var range = new DateRangeTester('2017-08-21 00:00:00', '2017-08-27 00:00:00');
var jsonArray = [
{
date: '2017-08-21',
edit: false,
text: 'some text'
},
{
date: '2017-08-28', // outside range
edit: false,
text: 'some text'
},
{
date: '2017-08-23', //not sure I understand your comment
edit: false,
text: 'some text'
},
{
date: '2017-08-20', // outside range
edit: false,
text: 'some text'
}
];
for(var i=0,ds,l=jsonArray.length; i<l; i++){
ds = jsonArray[i].date;
range.test(ds+' 00:00:00', function(r){
console.log(r+' passed the test');
}, function(r){
console.log(r+' failed the test');
});
}
&#13;