node.js - JavaScript: shorthand for conditionally adding something to an array -


i writing mocha test server @ work.

i 2 potential phone numbers customer, @ least 1 of defined.

    var homephone = result.homephone;     var altphone = result.altphone; 

i want use underscore's _.sample function pick 1 of these @ random. however, 1 of them may undefined.

so thinking like:

//pseudocode

var phone = _.sample([homephone || (donothing), altphone || (donothing)]); 

the _.sample function looks this: http://underscorejs.org/#sample

the problem of course, there no shorthand syntax know of conditionally add array.

the verbose way want is:

var phonearray = [];  if(homephone){  phonearray.push(homephone); } if(altphone){  phonearray.push(homephone); }  var phoneselection = _.sample(phonearray); 

is there more elegant way in javascript?

since you're using underscore, suggest leveraging compact:

var phone = _.sample(_.compact([homephone, altphone])); 

this shortened version of dave's answer, since compact literally implemented function(array) { return _.filter(array, _.identity); }.


Comments

Post a Comment

Popular posts from this blog

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -