Tsar Tsar - 1 year ago 72
Javascript Question

JavaScript function to compare values in the array and return it

Mods: feel free to paraphrase the question.
What I am trying to do is tell whether all values in the array for a given dynamic property are the same and, if true, return it.

I have achieved this in 3 lines using underscore.js, however, I was hoping this could be simplified/shortened:

var val = this.children[0]["myProperty"];
var same = _.all(this.children, child => child["myProperty"] === val);

return same ? val : null;

so that if:

this.children = [{"myProperty":null},{"myProperty":2},{"myProperty":1},{"myProperty":1}];

this.children = [{"myProperty":1},{"myProperty":1},{"myProperty":1},{"myProperty":1}];

N.B. the value of "myProperty" is a single digit whole number or null

Answer Source

with a dynamic property:

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download