miércoles, 12 de octubre de 2016

[Javascript] filter Function

Hi friends,

After testing Javascript filter sample of our friend DevCode () I've decided to optimize with javascript filter function for arrays.

The syntax it's:

array.filter(function(element){return condition_for_element});

Example:

index.html
<!DOCTYPE html>
<html lang="es">
<head>
<title>Buscador Javascript</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="source.js"></script>
</head>
<body>
<input type="text" id="buscar-pal" onkeyup="autocompletado2()" style="border: solid 2px" />
<div>
<ul id="demo"></ul>
</div>

</body>
</html>

source.js
function autocompletado2(){
document.getElementById("demo").innerHTML='';

var preguntas = [
"BASIC",
"C",
"C++",
"Java",
"Javascript",
"PHP",
"Python",
"Ruby"
];

var pal = document.getElementById("buscar-pal").value;
var tam = pal.length;
if(tam>0){
var filtrados = preguntas.filter(function(nombre){
var nombrelower = nombre.toLowerCase();
return nombrelower.indexOf(pal.toLowerCase()) != -1;
}
);
for(indice in filtrados){
var node = document.createElement("li");
var textnode = document.createTextNode(filtrados[indice]);
node.appendChild(textnode);
document.getElementById("demo").appendChild(node);
}
}
}

The result:




2 comentarios:

  1. Thanks for your feedback for It the!!!! In fact, I haven't much expertise in front, but I'm working in a project in angular and I'm liking it.
    Regrads.

    ResponderEliminar