I am trying to do array manipulations inside an arrays object as shown 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 the duplicates which have the same value for the key a but also before omitting that object, I want to compare among other duplicates and push the object which has true value for key x (if there are no true values available, then I will push the x: false value only).
I am open to use lodash or underscore to achieve this.
I tried using _.unionBy and _.uniqBy but I am unable to understand on how to consider x: true properly.
Using lodash.
Group by attribute a. Then merge objects inside each group; keep only truthy 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With