| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | [Back] [Original] |
Get to know MDN better
const words = ["spray", "elite", "exuberant", "destruction", "present"];
const result = words.filter((word) => word.length > 6);
console.log(result);
// : Array ["exuberant", "destruction", "present"]
filter(callbackFn)
filter(callbackFn, thisArg)
filter() callbackFn callbackFn callbackFn
filter() 10
function isBigEnough(value) {
return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(n) {
if (n < 2) {
return false;
}
if (n % 2 === 0) {
return n === 2;
}
for (let factor = 3; factor * factor <= n; factor += 2) {
if (n % factor === 0) {
return false;
}
}
return true;
}
console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
filter() id 0 JSON
const arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" },
];
let invalidEntries = 0;
function filterByID(item) {
if (Number.isFinite(item.id) && item.id !== 0) {
return true;
}
invalidEntries++;
return false;
}
const arrByID = arr.filter(filterByID);
console.log("\n", arrByID);
//
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
console.log(" =", invalidEntries);
// = 5
filter()
const fruits = ["apple", "banana", "grapes", "mango", "orange"];
/**
*
*/
function filterItems(arr, query) {
return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));
}
console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']
console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']
array map() ID filter()
const names = ["JC63", "Bob132", "Ursula89", "Ben96"];
const greatIDs = names
.map((name) => parseInt(name.match(/\d+/)[0], 10))
.filter((id, idx, arr) => {
// arr
//
if (idx > 0 && id <= arr[idx - 1]) return false;
if (idx < arr.length - 1 && id <= arr[idx + 1]) return false;
return true;
});
console.log(greatIDs); // [132, 96]
array
filter()
console.log([1, , undefined].filter((x) => x === undefined)); // [undefined]
console.log([1, , undefined].filter((x) => x !== 2)); // [1, undefined]
filter() this length length
const arrayLike = {
length: 3,
0: "a",
1: "b",
2: "c",
3: "a", // length 3 filter()
};
console.log(Array.prototype.filter.call(arrayLike, (x) => x <= "b"));
// [ 'a', 'b' ]
| ECMAScript 2027 LanguageSpecification # sec-array.prototype.filter |
Arrayat()concat()copyWithin()entries()every()fill()filter()find()findIndex()findLast()findLastIndex()flat()flatMap()forEach()includes()indexOf()join()keys()lastIndexOf()map()pop()push()reduce()reduceRight()reverse()shift()slice()some()sort()splice()toLocaleString()toReversed()toSorted()toSpliced()toString()unshift()values()with()[Symbol.iterator]()Object/Function| Web Proxy Viewer | New URL | Original Page |