从对象数组中删除重复项

csv*_*svb 3 javascript node.js

我有一些带有一些键和值的javascript对象.下面是我的数组的样子.

[
{
"timestamp": 1474328370007,
"message": "hello"
},
{
"timestamp": 1474328302520,
"message": "how are you"
},
{
"timestamp": 1474328370007,
"message": "hello"
},
{
"timestamp": 1474328370007,
"message": "hello"
}
]
Run Code Online (Sandbox Code Playgroud)

我想删除对象中时间戳的重复发生,并且只保留该对象的单个发生.匹配应基于时间戳而不是消息发生.

预期产量是

[
{
 "timestamp": 1474328302520,
"message": "how are you"
},
{
"timestamp": 1474328370007,
"message": "hello"
}
]
Run Code Online (Sandbox Code Playgroud)

尝试这样的事情

var fs = require('fs');

fs.readFile("file.json", 'utf8', function (err,data) {
if (err) console.log(err);;
console.log(data);
// var result = [];
for (i=0; i<data.length;i++) {
  if(data[i].timestamp != data[i+1].timestamp)
    console.log('yes');
  }
});
Run Code Online (Sandbox Code Playgroud)

data[i+1]数组结束后我无法弄清楚该部分.有没有简单的方法可以进行上述重复数据删除?

先感谢您

Nin*_*olz 5

您可以将对象用作哈希表并进行检查.

var array = [{ "timestamp": 1474328370007, "message": "hello" }, { "timestamp": 1474328302520, "message": "how are you" }, { "timestamp": 1474328370007, "message": "hello" }, { "timestamp": 1474328370007, "message": "hello" }],
    result = array.filter(function (a) {
        return !this[a.timestamp] && (this[a.timestamp] = true);
    }, Object.create(null));

console.log(result);
Run Code Online (Sandbox Code Playgroud)

您可以使用散列的变量和过滤结果的变量,例如

var hash = Object.create(null),
    result = [];

for (i = 0; i < data.length; i++) {
    if (!hash[data[i].timestamp]) {
        hash[data[i].timestamp] = true;
        result.push(data[i]);
    }
}
Run Code Online (Sandbox Code Playgroud)