# Checking if any competitors have a non-empty name [closed]

Take this:

has_competitors:function(){
var c = false;
_.each(this.competitors, function(obj, index){ // lodash here
if(obj.name && obj.name.trim() !== ''){
c = true;
return false; // to break the loop
}
});
return c;
}


I don't like the form of this, but till now I didn't find a more concise way. Could you suggest a better way? :) I mean, less lines.

• What does this function do? Please tell us, and make that the title of the question — see How to Ask. Also tell us what _ is — use the lodash.js or underscore.js tag as appropriate. – 200_success Jul 25 '18 at 14:03
• There were already enough informations to have 2 answers and one accepted, so I don't really see the point. Anyway, added the informations you're asking for. – Luca Reghellin Jul 26 '18 at 21:50

I assume you are using lodash library.

You may use _.some function.

Checks if predicate returns truthy for any element of collection. Iteration is stopped once predicate returns truthy. The predicate is invoked with three arguments: (value, index|key, collection).

has_competitors: function(){
return _.some(this.competitors, function(obj){
return obj.name && obj.name.trim() !== '';
};
}

• Since ES5 (which all browsers support nowadays) is array.some(). It works in the same way as Lodash's/Underscore's _.some() but without the library.
• If you target ES6, you can further trim your code using shorthand object methods and arrow functions.
• Your object.trim() can blow up if object.name is truthy but not a string. Do a typeof obj.name === 'string' instead of a truthy check. If it is always guaranteed to be a string, the truthy check is redundant since a trimmed empty string will always be empty.

So your code could be as simple as:

has_competitors(){
return this.competitors.some(obj => obj.name.trim() !== '')
}

• Good suggestions. Anyway in my case competitors is a collection (obj) not an array, so I'll go for lodash. – Luca Reghellin Jul 26 '18 at 7:50