独特的日期数组Javascript [英] Unique Array for dates Javascript

查看:79
本文介绍了独特的日期数组Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到这个问题经常用于常规的javascript数组,但是如果它的日期数组没有任何答案似乎都有效。

I see this question asked quite often for regular javascript arrays, however none of the answers seems to work if its an array of dates.

我可能会想到这个通过试验出错,但如果我问的话,我确实看到了其他人的好处。

I can likely figure this out through trial an error but I do see some benefit to others if I ask.

基本上,如果你有一个日期的javascript数组可能有重复,需要过滤到一个没有重复的数组最好的方法是什么?

Basically if you have a javascript array of dates that might have duplicates and need to filter into an array with no duplicates what is the best way to go about that?

我已经尝试了的数组解决方案(新的Set( arr))但它只返回相同的数组。

I have tried the ES6 solution of Array.from(new Set(arr)) but it just returns the same array.

我也试过

Array.prototype.unique = function() {
    var a = [];
    for (var i=0, l=this.length; i<l; i++)
        if (a.indexOf(this[i]) === -1)
            a.push(this[i]);
    return a;
}

均来自数组中的唯一值

但是没有效果,看起来像 indexOf 对日期对象不起作用。

However neither worked, looks like indexOf does not work on date objects.

以下是我的数组生成方式atm

Here is how my array is generated atm

//this is an array generated from ajax data, 
//its a year over year comparison with a separate year, 
//so to create a reliable date objects I force it to use the same year.
data.map(d => {
   dp = new Date(Date.parse(d.date + '-' + d.year));
   dp.setFullYear(2000);
   return dp;
})

大约100左右不同天,但它总是以350左右的索引结束。

It is about 100 or so different days, but it always ends up with about 350 index's.

推荐答案

如果你通过 =比较两个日期= == ,比较两个日期对象的引用。表示相同日期的两个对象仍然是不同的对象。

If you compare two dates via ===, you compare the references of the two date objects. Two objects that represent the same date still are different objects.

相反,比较来自 Date.prototype.getTime()

function isDateInArray(needle, haystack) {
  for (var i = 0; i < haystack.length; i++) {
    if (needle.getTime() === haystack[i].getTime()) {
      return true;
    }
  }
  return false;
}

var dates = [
  new Date('October 1, 2016 12:00:00 GMT+0000'),
  new Date('October 2, 2016 12:00:00 GMT+0000'),
  new Date('October 3, 2016 12:00:00 GMT+0000'),
  new Date('October 2, 2016 12:00:00 GMT+0000')
];

var uniqueDates = [];
for (var i = 0; i < dates.length; i++) {
  if (!isDateInArray(dates[i], uniqueDates)) {
    uniqueDates.push(dates[i]);
  }
}

console.log(uniqueDates);

优化和错误处理取决于你。

Optimization and error handling is up to you.

这篇关于独特的日期数组Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆