Reputation: 95
I have more than two arrays with objects which have some similar properties, and I want to merge all arrays to one array and sort theme as bellow:
array = [
[ { "name" : "Jack", count: 10 }, { "name": "Fred", "count": 20 } ],
[ { "name": "Jack", count: 3 }, { "name": "Sara", "count": 10 } ]
]
merged_array = [
{ "name": "Fred", "count": 20 },
{ "name": "Jack", "count": 13 },
{ "name": "Sara", "count": 10 }
]
Upvotes: 1
Views: 50
Reputation: 5524
If you are open to, then do take a look at to underscorejs, it is a wonderful utility for working with Arrays and objects as such. This will allow you to write flexible and transparent logic. The documentation is also quite good.
var arrays = [
[{
"name": "Jack",
count: 10
}, {
"name": "Fred",
"count": 20
}],
[{
"name": "Jack",
count: 3
}, {
"name": "Sara",
"count": 10
}]
]
var result = _.chain(arrays)
.flatten()
.union()
// whatever is the "key" which binds all your arrays
.groupBy('name')
.map(function(value, key) {
var sumOfCount = _.reduce(value, function(entry, val) {
// the fields which will need to be "aggregated"
return entry + val.count;
}, 0);
return {
'name': key,
'count': sumOfCount
};
}
)
// you can have your own sorting here
.sortBy('count')
.value();
console.log(result.reverse());
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Upvotes: 0
Reputation: 122057
You can use two forEach()
to get array with merged objects and then sort it with sort()
.
var array = [
[{
"name": "Jack",
count: 10
}, {
"name": "Fred",
"count": 20
}],
[{
"name": "Jack",
count: 3
}, {
"name": "Sara",
"count": 10
}]
]
var result = [];
array.forEach(function(a) {
var that = this;
a.forEach(function(e) {
if (!that[e.name]) {
that[e.name] = e;
result.push(that[e.name]);
} else {
that[e.name].count += e.count
}
})
}, {})
result.sort(function(a, b) {
return b.count - a.count;
})
console.log(result)
Upvotes: 1
Reputation: 989
array
.reduce(function(result, arrayItem) {
result = result || [];
// sort also can be implemented here
// by using `Insertion sort` algorithm or anyone else
return result.concat(arrayItem);
})
.sort(function(a,b) { return a.count < b.count; })
Upvotes: 1