Overview
Implement filter(array, callback) that returns a new array of elements for which callback returns truthy.
Examples
filter([1,2,3,4], x => x > 2); // [3,4]
Solution
Reveal solution
function filter(array, callback) {
const r = [];
for (let i = 0; i < array.length; i++) {
if (callback(array[i], i, array)) r.push(array[i]);
}
return r;
}array-prototype-filter.js
Array.prototype.filter
easycodingJavaScriptArrays
Overview
Implement filter(array, callback) that returns a new array of elements for which callback returns truthy.
Examples
filter([1,2,3,4], x => x > 2); // [3,4]
Solution
Reveal solution
function filter(array, callback) {
const r = [];
for (let i = 0; i < array.length; i++) {
if (callback(array[i], i, array)) r.push(array[i]);
}
return r;
}NameTopicDifficulty
103 of 103 problems