Example 1: filter javascript
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filter = arr.filter((number) => number > 5);
console.log(filter); // [6, 7, 8, 9]
or
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Example 2: array filter
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Example 3: array.filter in javascript
//Eg 1 - If item is unchecked, remove it from array
const array = [2, 3, 4]
if (event.target.checked) {
newValue.push(option);
} else {
newValue = newValue.filter(item => item.id != option.id);
}
//If false, it will remove the element. 2 is not equal to 2.
//Eg 2 - To return an array with length > 6
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
Example 4: js filter items by index
let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])