Check if array contains object-only-element in Javascript -
i want check if array contains only objects. created function:
function arraycontainsobjonly(arr){ return arr.join("").replace(/\[object object\]/g, "") === ""; } here how use it:
// return true arraycontainsobjonly([ {"name" : "juan", "age" : 28}, {"name" : "pedro", "age" : 25} ]); // return false arraycontainsobjonly([ {"name" : "juan", "age" : 28}, "name=pedro;age=25" ]); is there cleaner way this? using literal "[object object]" checking safe? prefer non-jquery solution.
conceptually simpler , cleaner, no less code:
function arrcontainsobjonly(arr) { return arr.every(function(el) { return object.prototype.tostring.call(el) === '[object object]'; }); } update
on second thought, variant better, return false on encountering first non-object:
function arrcontainsobjonly(arr) { return !arr.some(function(el) { return object.prototype.tostring.call(el) !== '[object object]'; }); }
Comments
Post a Comment