For arrays like [ true , 1, 'car', { a: '1' }]
how can I use reduce to evaluate that the entire array is true or false? It has to consider truthy and falsey values.
Moreover, using reduce, if all values are truthy return true. If the elements are mixed with truthy and falsey values return false. If the elements are all falsey return false.
I also cannot use every. I am actually trying to implement the every method by using reduce as an assignment. It works it just doesn't pass for all-truthy results nor does it cast the result to a bool bonus question :) if I have
_.every([1], _.identity)).to.be.true;
_.every([0], _.identity)).to.be.false;
Also is {} truthy? bonus bonus question
Here's my code but it doesn't use reduce which is probably making it harder to evaluate the truthy, falsey and mixed values. Thanks for your help!
_.every = function(collection, iterator) {
// TIP: Try re-using reduce() here.
var results = [];
if ( iterator === undefined ) {
_.each( collection , function( item ) {
results.push( item );
});
} else {
if ( Array.isArray( collection ) === true ) {
var copiedArr = collection.slice();
// iterate through each item using each
_.each( collection , function( item ) {
// input our own iterator calling truth test
if ( iterator( item ) === true ) {
// store results in array
results.push( true )
} else {
results.push( false );
}
} );
} else if ( typeof collection === 'object' ) {
var copiedObj = JSON.parse(JSON.stringify( collection ));
// iterate through each item using each
_.each( copiedObj , function( item ) {
// input our own iterator calling truth test
if ( iterator( item ) === true ) {
// store results in array
results.push( true )
} else {
results.push( false );
}
});
}
} // end of iterator defined else
// if array contains false return false
if ( _.contains( results , false) ) {
return false
} else {
// else return true
return true;
}
} // end of _.every
```