javascript filtering code example
Example 1: javascript object filter
function objectFilter = (obj, predicate) =>
Object.keys(obj)
.filter( key => predicate(obj[key]) )
.reduce( (res, key) => (res[key] = obj[key], res), {} );
// Example use:
var scores = {
John: 2, Sarah: 3, Janet: 1
};
var filtered = objectFilter(scores, num => num > 1);
console.log(filtered);
Example 2: filter in js
const filterThisArray = ["a","b","c","d","e"]
console.log(filterThisArray) // Array(5) [ "a","b","c","d","e" ]
const filteredThatArray = filterThisArray.filter((item) => item!=="e")
console.log(filteredThatArray) // Array(4) [ "a","b","c","d" ]
Example 3: javascript array filter
run.addEventListener("click", function () {
let array = [];
people.forEach((elem) => {
// elem before age to target
if (elem.age > 18) {
array.push(elem); // each array elem > 18 is "pushed" inside the new array
// console.log(array); nope : messes things up
} else {
(""); // no need to declare this through console.log
}
});
console.log(array); //and there you have it : filtered array
});
Example 4: js filter items by index
let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])