I am trying to merge recurring object within an array while adding some of their attributes value and concatenating on attribute into an array, but I am stuck.
Here's the kind of array I am processing :
[{
"Favorites": 0,
"Frequency": 1,
"Hashtag": "19h30",
"Replies": 0,
"Retweets": 1,
"tweetId": 615850479952785400
}, {
"Favorites": 0,
"Frequency": 1,
"Hashtag": "80s",
"Replies": 0,
"Retweets": 1,
"tweetId": 617319253738393600
}, {
"Favorites": 0,
"Frequency": 1,
"Hashtag": "80s",
"Replies": 0,
"Retweets": 1,
"tweetId": 616521677275533300
}, {
"Favorites": 1,
"Frequency": 1,
"Hashtag": "AloeBlacc",
"Replies": 0,
"Retweets": 1,
"tweetId": 617309488572420100
}, {
"Favorites": 2,
"Frequency": 1,
"Hashtag": "Alpes",
"Replies": 0,
"Retweets": 1,
"tweetId": 615481266348146700
}]
And the end result I am hoping to find :
[{
"Favorites": 0,
"Frequency": 1,
"Hashtag": "19h30",
"Replies": 0,
"Retweets": 1,
"tweetId": 615850479952785400
}{
"Favorites": 0,
"Frequency": 2,
"Hashtag": "80s",
"Replies": 0,
"Retweets": 2,
"tweetId": [617319253738393600 ,
616521677275533300]
}, {
"Favorites": 1,
"Frequency": 0,
"Hashtag": "AloeBlacc",
"Replies": 0,
"Retweets": 1,
"tweetId": 617309488572420100
}, {
"Favorites": 2,
"Frequency": 0,
"Hashtag": "Alpes",
"Replies": 0,
"Retweets": 1,
"tweetId": 615481266348146700
}]
For the moment, I tried looping within a loop but with no success and I am stuck.
var mergedHashtags = [];
var merged={};
for (var i = 0; i < hashtags.length-1; i++) {
var a = hashtags[i];
// start second loop at next element in array
for (var j = i+1; j < hashtags.length; j++) {
var b = hashtags[j];
console.log('a',a,'b',b, 'i',i,'j',j);
if (a.Hashtag===b.Hashtag) {
var tIds = [a.tweetId];
merged.Hashtag = a.Hashtag;
merged.tweetId = tIds.concat(b.tweetId);
merged.Favorites = a.Favorites+b.Favorites;
merged.Retweets = a.Retweets+b.Retweets;
merged.Replies = a.Replies+b.Replies;
merged.Frequency = a.Frequency+b.Frequency;
mergedHashtags.push(merged);
console.log('same', merged);
continue;
}else{
mergedHashtags.push(a);
i=j-1;
console.log('diff',a);
break;
}
}
}
I will appreciate your help a lot !
Thanks in advance Q.