Javascript Array filter(f)
const { books } = require('../books.js'); Array.prototype._filter = function(f){ let result = []; this.forEach(item =>{//from w w w . ja v a 2 s .c om if(f(item)){ result.push(item) } }); return result; }; //const booksMaxPages = books._filter(book => book.pages > 400); const funcBookMax = book => book.pages > 400; const booksMaxPages = books._filter(funcBookMax); console.log(booksMaxPages);
// complete the following such that a new array with only integers // (while numbers) is returned var arr = ['hello', 42, true, function() {}, "123", 3.14, 0, [1], {}]; var isInteger = function(x) { return (typeof x === 'number' && isFinite(x) && Math.floor(x) === x); } Array.prototype.filter = function(f) { var newArr = []; for (var i = 0; i < this.length; i++) { if (f(this[i])) newArr.push(this[i]); }//from ww w . j a v a2 s. c o m return newArr; }; var newArr = arr.filter(isInteger); console.log(newArr);
Array.prototype.filter = function(f) { var filtered = []; for(var i = 0; i < this.length; i++) f(this[i], i) && filtered.push(this[i]); return filtered; };