collections-reject1
by shan10213223
JavaScript
var _ = {};
// _.reject(collection, predicate, [context])
// Looks through each value in the collection, returning an array of all the values
// that don't pass a truth test (predicate). Predicate is called with three arguments:
// (element, index|key, collection), and bound to the context if one is passed.
// TIP: can you reuse _.filter()?
_.reject = function (collection, predicate, context) {
let results = [];
/*for (let i=0; i<collection.length; i++) {
results.push(collection[i]);
}*/
collection.forEach(function(element) {
if (!predicate(element)) {
results.push(element);
}
});
return results;
};
// test 1
// https://stackoverflow.com/questions/11924976/filter-through-js-objects-using-underscore-js
var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
console.log(evens);
//=> [2, 4, 6]
// test 2
var questions = [
{question: "what is your name"},
{question: "How old are you"},
{question: "whats is your mothers name"},
{question: "where do work/or study"},
];
var slected_questions = _.reject(questions, function(obj) {
// `~` with `indexOf` means "contains"
// `toLowerCase` to discard case of question string
return ~obj.question.toLowerCase().indexOf("how");
});
console.log(slected_questions);