Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove duplicates from a array of objects [duplicate]

I have a array of javascript objects with some key and value. Below is how my array looks like.

[
{
"timestamp": 1474328370007,
"message": "hello"
},
{
"timestamp": 1474328302520,
"message": "how are you"
},
{
"timestamp": 1474328370007,
"message": "hello"
},
{
"timestamp": 1474328370007,
"message": "hello"
}
]

I want to remove the duplicate occurring of timestamp in the object and keep only single occurring of that object. The matching should happen based on the timestamp and not the message.

expected output is

[
{
 "timestamp": 1474328302520,
"message": "how are you"
},
{
"timestamp": 1474328370007,
"message": "hello"
}
]

trying something like this

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');
  }
});

I cannot figure out the data[i+1] part after the array ends. Is there any easy way with which I can do the above deduplication?

thank you in advance

like image 584
csvb Avatar asked Nov 25 '16 19:11

csvb


People also ask

How do you filter duplicate values in an array?

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.

How do you find duplicate objects in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.


1 Answers

You could use an object as hash table and check against.

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);

You could use a variable for the hash and one for the filtered result, like

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]);
    }
}
like image 95
Nina Scholz Avatar answered Sep 24 '22 00:09

Nina Scholz