Here the solution using lodash and uniqWith function: JSFiddle.
Here's the code:
function merge(array) {
return _.uniqWith(array, compareAndMerge)
}
function compareAndMerge(first, second) {
if (first.field === second.field) {
first.values = second.values = [].concat(first.values, second.values)
return true
}
return false
}
var data = [{
field: 'Currency',
operator: 'IN',
values: ['usd']
}, {
field: 'Currency',
operator: 'IN',
values: ['gbp']
}, {
field: 'Amount',
operator: 'IN',
values: [2]
},
{
field: 'Amount',
operator: 'IN',
values: [3]
}]
console.log(merge(data))
Lodash.uniqWidth function wants an array and a comparator. In case of equal fields we edit values of the two compared elements assigning the concatenation of the two values arrays.
Something more: it's a transgression to edit objects inside the comparator, but I think that it could run safely.