Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uniq two array objects and give priority to true value

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.

like image 827
Mr_Green Avatar asked May 17 '26 06:05

Mr_Green


1 Answers

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>
like image 133
SeregPie Avatar answered May 18 '26 19:05

SeregPie