如何按日期计算对象数组中的出现次数

时间:2016-04-25 11:58:39

标签: javascript arrays json date find-occurrences

我正在使用TypeScript或JavaScript搜索功能强大的解决方案来计算对象数组中的匹配项。我希望通过日期来做到这一点。 (我需要它来创建一些图表)

例如,我有这个数组:

var arr2 = [
        {date: Wed Jan 20 2016 
            type: ["Apples", 1]}, 
        {date: Mon Feb 29 2016
            type: ["Peaches",1]},
        {date: Thu Mar 31 2016 
            type: ["Apples",1]},
        {date: Fri Apr 22 2016 
            type: ["Apples",3],["Strawberries",1]}
    ]

我希望得到的结果是下一个:

public class GridRecycleActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       /*toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        assert getSupportActionBar() != null;
        getSupportActionBar().setHomeButtonEnabled(true);*/
        suffle = (Button) findViewById(R.id.suffle);

        for (int i = 0; i < Glob.imgs.length; i++) {
            data.add(new ImageData(Glob.imgs[i]));
        }


        try {
            recyclerView = (RecyclerView) findViewById(R.id.recycleGridView);
            //recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
            recyclerView.setHasFixedSize(true);
            recyclerView.setAdapter(adapter);


        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        try {
            suffle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Collections.shuffle(data);
                    adapter = new Recycle_Adapter(mContext, data);
                    recyclerView.swapAdapter(adapter, false);
                    recyclerView.setItemAnimator(new FlipInBottomXAnimator());
                    recyclerView.getItemAnimator().setMoveDuration(5000);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

    }

我不知道为什么,但我无法找到一个好的解决方案,我在某些日子里正在努力...

如果有人知道技巧,功能或其他什么?

4 个答案:

答案 0 :(得分:2)

应该像这样工作:

var x = new Date().getTime(),
    filtered = arr.filter( function (obj) { return obj.date.getTime() >= x }),
    occurenceCount = filtered.length;

我使用getTime()将日期转换为整数,因为我有比较Date对象bevor的奇怪行为。 arr2将包含x之后的所有日期(在此示例中为NOW),count将返回arr2中包含的元素数。

答案 1 :(得分:2)

试试这个

首先创建一个地图

var map = {}; arr.forEach(function(val){
  map[val.date] = map[val.date] || {};
  map[val.date][val.type] = map[val.date][val.type] || 0;
  map[val.date][val.type]++;
});

现在获得输出

var output = Object.keys(map).map(function(key){
  var tmpArr = [];
  for(var type in map[key])
  {
     tmpArr.push( [ type, map[key][type] ] )
  }
  return { date : key, type: tmpArr  };
})

<强>样本

var arr = [
    {date: "Wed Jan 20 2016",
        type: "Apples"}, 
    {date: "Mon Feb 29 2016",
        type: "Peaches"},
    {date: "Thu Mar 31 2016",
        type: "Apples"},
    {date: "Fri Apr 22 2016" ,
        type: "Apples"},
    {date: "Fri Apr 22 2016" ,
        type: "Apples"},
    {date: "Fri Apr 22 2016" ,
        type: "Apples"},
    {date: "Fri Apr 22 2016" ,
        type: "Strawberries"}
]


    var map = {}; arr.forEach(function(val){
      map[val.date] = map[val.date] || {};
      map[val.date][val.type] = map[val.date][val.type] || 0;
      map[val.date][val.type]++;
    });


    var output = Object.keys(map).map(function(key){
      var tmpArr = [];
      for(var type in map[key])
      {
         tmpArr.push( [ type, map[key][type] ] )
      }
      return { date : key, type: tmpArr  };
    })

    document.body.innerHTML += JSON.stringify(output,0,4);

答案 2 :(得分:1)

使用ISO日期和临时对象这样的正确日期格式,您可以使用Array#forEach循环并返回想要的结果。它可以在一个循环中工作。

&#13;
&#13;
var array = [{ date: '2016-01-20', type: "Apples" }, { date: '2016-02-29', type: "Peaches" }, { date: '2016-03-31', type: "Apples" }, { date: '2016-04-22', type: "Apples" }, { date: '2016-04-22', type: "Apples" }, { date: '2016-04-22', type: "Apples" }, { date: '2016-04-22', type: "Strawberries" }],
    grouped = [];

array.forEach(function (a) {
    var key = a.date + '|' + a.type;
    if (!this[a.date]) {                
        this[a.date] = { date: a.date, type: [] };;
        grouped.push(this[a.date]);
    }            
    if (!this[key]) {
        this[key] = [a.type, 0];
        this[a.date].type.push(this[key]);
    }
    this[key][1]++;
}, Object.create(null));

document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 3 :(得分:-2)

过滤数组并检查过滤器功能中的日期。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

function findItemsByDate(value) {
    // find if an item already exists with the date index
    var dateIndex = arr2.findIndex(findDateIndex);
    // create an array or use the existing one based on result
    if(dateIndex === -1){
      var dateArray = []
    }else{
      dateArray = arr2[dateIndex];
    }
    // find the type object based on the input type and add to it, or create a new one.
    if(dateArray.type.hasOwnProperty(value.type)){
       dateArray.type[value.type] += 1;
    }else{
      dateArray.type[value.type] = 1;
    }
}
// utility function to see if an item already exists in the new array with the key for the date.
function findDateIndex(item, index, arr){
        if(item.date = "Thu Mar 31 2016"){
            alert("Has Data")
        return index;
    }
    return -1;
  }

这将返回与您正在寻找的略有不同但更易于管理的结果。

var arr2 = [
        {date: "Wed Jan 20 2016", type: ["Apples", 1]}, 
        {date: "Mon Feb 29 2016",type: ["Peaches",1]},
        {date: "Thu Mar 31 2016", type: ["Apples",1]},
        {date: "Fri Apr 22 2016", type: {"Apples":3,"Strawberries":1}}
    ]