Filtro de matriz JavaScript()
Exemplo 1
Retorne uma matriz de todos os valores em idades[] com 18 anos ou mais:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
Definição e uso
O filter()
método cria um novo array preenchido com elementos que passam em um teste fornecido por uma função.
O filter()
método não executa a função para elementos vazios.
O filter()
método não altera a matriz original.
Sintaxe
array.filter(function(currentValue, index, arr), thisValue)
Parâmetros
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. |
Valor de retorno
Modelo | Descrição |
Uma matriz |
Contendo os elementos que passam no teste. Se nenhum elemento passar no teste, ele retornará um array vazio. |
Suporte ao navegador
filter()
é um recurso ECMAScript5 (ES5).
ES5 (JavaScript 2009) totalmente suportado em todos os navegadores:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
Exemplo 2
Retorne os valores em idades[] que estão acima de um número específico:
<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>