Mods:随意解释这个问题。 我想要做的是判断数组中给定动态属性的所有值是否相同,如果 true ,则返回它。
我使用underscore.js在3行中实现了这一点,但是,我希望这可以简化/缩短:
var val = this.children[0]["myProperty"];
var same = _.all(this.children, child => child["myProperty"] === val);
return same ? val : null;
以便:if:
this.children = [{"myProperty":null},{"myProperty":2},{"myProperty":1},{"myProperty":1}];
...返回null
this.children = [{"myProperty":1},{"myProperty":1},{"myProperty":1},{"myProperty":1}];
...返回1
N.B。 “myProperty”的值是单个数字整数或null
答案 0 :(得分:1)
这似乎有用,使用vanilla javascript和reduce
,或者它可能会让你朝着正确的方向发展:
function children(arr,prop){
return arr.reduce(
function(prevVal,curVal){
return prevVal == curVal[prop] ? prevVal : null
},
arr[0][prop]
);
}
children([{"myProperty":null},{"myProperty":2},{"myProperty":1},{"myProperty":1}],'myProperty')
> null
children([{"myProperty":1},{"myProperty":1},{"myProperty":1},{"myProperty":1}],'myProperty')
> 1
或
Array.prototype.children = function(prop){
return this.reduce(
function(prevVal,curVal){
return prevVal == curVal[prop] ? prevVal : null
},
this[0][prop]
);
}
[{"myProperty":null},{"myProperty":2},{"myProperty":1},{"myProperty":1}].children('myProperty')
> null
[{"myProperty":1},{"myProperty":1},{"myProperty":1},{"myProperty":1}].children('myProperty')
> 1
答案 1 :(得分:1)
具有动态属性:
var prop = "myProperty";
//vanilla JS
return this.children.map(o => o[prop]).reduce((acc, v) => acc === v? v: null);
//and underscore
return _.reduce(_.pluck(this.children, prop), (acc, v) => acc === v? v: null);
答案 2 :(得分:0)
您自己的解决方案会尽快返回否定结果。它仍然是O(n),但如果children
很大并且值很少相等,则差异可能是合理的(几乎从不)。在vanilla JS中,使用.every
:
function childrenValue(prop) {
var first = this.children[0][prop];
return this.children.every(child => child[prop] === first) ? first : null;
}