Uniq two array objects and give priority to true value
I am trying to manipulate arrays inside an array object like below:
var first = [{
a: "one",
x: false
}, {
a: "two",
x: true
}, {
a: "three",
x: false
}, {
a: "one",
x: true
}, {
a: "two",
x: true
}, {
a: "four",
x: false
}];
Expected Result:
// Result
[{
a: "one",
x: true
}, {
a: "two",
x: true
}, {
a: "three",
x: false
}, {
a: "four",
x: false
}];
As you can see, I am trying to omit duplicates that have the same value for the key a
, but also before omitting that object, I want to compare between other duplicates and push the object that has a true value for the key x
(if there are no true values ββavailable, then I only push the value x: false
).
I can use lodash
or underscore
to achieve this.
I have tried using _.unionBy
and _.uniqBy
, but I cannot figure out how to count correctly x: true
.
source to share
Using lodash.
Group by attribute a
. Then combine the objects within each group; keep only true values.
let array = [
{a: 'one', x: false},
{a: 'two', x: true},
{a: 'three', x: false},
{a: 'one', x: true},
{a: 'two', x: true},
{a: 'four', x: false},
];
let result = _(array)
.groupBy('a')
.map(objects => _.mergeWith(...objects, (a, b) => a || b))
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
source to share