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

.

+3


source to share


3 answers


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>
      

Run codeHide result


+1


source


var results = [];

first.forEach(f => {
   var index = results.map(r => r.a).indexOf(f.a);

   if(index === -1) {
      results.push(f)
   } else {
      f.x && (results[index].x = true);
   }
})

      



0


source


var unique = _.uniqWith(first, _.isEqual);
var result = unique.filter((item) => {
    if (item.x) return true;
    var sameA = unique.filter((i) => i.a === item.a);
    return sameA.length === 1;
});

      

0


source







All Articles