Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript uniq两个数组对象,并优先考虑真值_Javascript_Arrays_Underscore.js_Lodash - Fatal编程技术网

Javascript uniq两个数组对象,并优先考虑真值

Javascript uniq两个数组对象,并优先考虑真值,javascript,arrays,underscore.js,lodash,Javascript,Arrays,Underscore.js,Lodash,我正在尝试在arrays对象内执行数组操作,如下所示: 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 }]; 预期结果: // Result

我正在尝试在arrays对象内执行数组操作,如下所示:

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
}];
预期结果:

// Result
[{
    a: "one",
    x: true
}, {
    a: "two",
    x: true
}, {
    a: "three",
    x: false
}, {
    a: "four",
    x: false
}];
如您所见,我正试图忽略键
a
具有相同值的重复项,但在忽略该对象之前,我想比较其他重复项,并推送键
x
具有真值的对象(如果没有真值可用,那么我将只推送
x:false
值)

我愿意使用
lodash
下划线来实现这一点

<>我尝试使用<代码> .UNIONB< <代码> >代码> > UNIQBY 但我无法理解如何正确地考虑<代码> X:真< /代码>。< /P> < P>使用Loasy.< /P>
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);
   }
})
按属性分组
a
。然后合并每组内的对象;只保留真实的价值观

let数组=[
{a:'1',x:false},
{a:'two',x:true},
{a:'3',x:false},
{a:'1',x:true},
{a:'two',x:true},
{a:'four',x:false},
];
let result=389;(数组)
.groupBy('a')
.map(objects=>124;.mergeWith(…objects,(a,b)=>a | | b))
.value();
控制台日志(结果)
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;
});