how to use array.filter javascript code example
Example 1: filter
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(num) {
for (let i = 2; num > i; i++) {
if (num % i == 0) {
return false;
}
}
return num > 1;
}
console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
Example 2: 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
});