Filtro array JavaScript()
Esempio 1
Restituisce una matrice di tutti i valori in età[] che hanno 18 anni o più:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
Definizione e utilizzo
Il filter()
metodo crea un nuovo array riempito con elementi che superano un test fornito da una funzione.
Il filter()
metodo non esegue la funzione per gli elementi vuoti.
Il filter()
metodo non modifica l'array originale.
Sintassi
array.filter(function(currentValue, index, arr), thisValue)
Parametri
Parameter | Description |
function() | Required. A function to run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined A value passed to the function as its this value. |
Valore di ritorno
Tipo | Descrizione |
Un array |
Contenente gli elementi che superano il test. Se nessun elemento supera il test, restituisce un array vuoto. |
Supporto browser
filter()
è una funzione ECMAScript5 (ES5).
ES5 (JavaScript 2009) completamente supportato in tutti i browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
Esempio 2
Restituisci i valori in età[] che superano un numero specifico:
<p><input type="number" id="ageToCheck" value="30"></p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
const ages = [32, 33, 12, 40];
function checkAge(age) {
return age > document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAge);
}
</script>