如何比较输出的过去值?

时间:2018-03-09 07:44:18

标签: javascript arrays

有人知道如何比较下面的图像,我很难解决这个问题。 :)非常感谢你:))

输出在for循环中。我只是想比较和数数。

以下示例代码。

var array_date = ["2018/03/07","2018/03/07","2018/03/07","2018/03/07","2018/03/07","2018/03/08","2018/03/09","2018/03/09"];

var eventType = ["Absent","Absent","Late","Late","Late","Absent","Absent","Late"];

var prev_array_date="";
var prev_eventType="";
for(i = 0; i <array_date.length; i++){
console.log("sort_unique_arr_date[b]: "+array_date[i]);
console.log("temp_eventType: "+eventType[i]);
console.log("---------------------------------------------------------")

if(prev_array_date == "" && prev_eventType == ""){
prev_array_date = array_date[i];
prev_eventType = eventType[i];

}else{
  if(prev_array_date == array_date[i] && prev_eventType == eventType[i]){
  
  }
  else{
  
  }

}



}

我只想要这样的输出:

Output:

2018/03/07
Absent - 2

2018/03/07
Late - 3

2018/03/08
Absent - 1

2018/03/09
Absent - 1

2018/03/09
Late - 1

Console image

1 个答案:

答案 0 :(得分:1)

您可以在对象中使用日期和类型作为索引,并根据需要轻松填充它。 尝试使用以下代码,它应该做你想做的事情

var array_date = ["2018/03/07","2018/03/07","2018/03/07","2018/03/07","2018/03/07","2018/03/08","2018/03/09","2018/03/09"];

var eventType = ["Absent","Absent","Late","Late","Late","Absent","Absent","Late"];

var count_obj = {};
for(i = 0; i <array_date.length; i++){
  console.log("sort_unique_arr_date[b]: "+array_date[i]);
  console.log("temp_eventType: "+eventType[i]);
  console.log("---------------------------------------------------");
  let key = array_date[i];
  let s_key = eventType[i];
  if( ! count_obj.hasOwnProperty(key) ){
        count_obj[ key ] = {};
  }
  if( ! count_obj[ key ].hasOwnProperty(s_key) ){
        count_obj[ key ][ s_key ] = 0;
  }

    count_obj[ key ][ s_key ] += 1;

}
console.log("--OUTPUT BELOW--");
for( date in count_obj){
    console.log(date);
    for( type in count_obj[date] ){
        // if you put 'console.log(date);' here you'll have exactly the output you wanted
        console.log(type +' - '+count_obj[date][type]);
    }
}

检查Fiddle