var data = [
{
_id: '001',
name: 'Elon Musk',
rol: 'Chairman',
image: 'https://picsum.photos/200/101',
email: '[email protected]',
phone: '5544332211',
active: true,
exp: 30
},
{
_id: '002',
name: 'Carlos Hernandez',
rol: 'Chief Operation Officer',
image: 'https://picsum.photos/200/102',
email: '[email protected]',
phone: '5544332211',
active: true,
exp: 15
},
{
_id: '003',
name: 'Alberto Siurob',
rol: 'Chief Information Officer',
image: 'https://picsum.photos/200/103',
email: '[email protected]',
phone: '5544332211',
active: false,
exp: 5
},
{
_id: '004',
name: 'Erick Lopez',
rol: 'Chief Marketing Officer',
image: 'https://picsum.photos/200/104',
email: '[email protected]',
phone: '5544332211',
active: true,
exp: 1
},
];
function search( value ){
// Si no esta vacio
if( value ) {
const keys = ['name', 'email', 'rol'];
const match = searchKeys( data, keys, value.toLowerCase() );
console.log( match );
}
}
function searchKeys( source, keys, word ){
const arr = [];
// Recorrer llaves de busqueda
keys.forEach( ( k ) => {
// Recorrer la fuente
source.forEach( ( s ) => {
// validar si el indice tiene un valor semejante
if ( s[ k ].toLowerCase().includes( word ) ) {
// validar si ya existe en el arreglo
if ( arr.indexOf( s._id ) < 0 ) {
arr.push( s );
}
}
});
});
return arr;
}
<input type="text" onkeyup="search( this.value )">
I am making a small browser with the benefits of Javascript. The truth is that it works very well, but I have a problem that if I only put a letter in the input, it triples the returned results.
What will I be doing wrong?
PS: If you have any suggestions to do it in a better way, it is always welcome
Your problem is that the array
arr
is an array of objects so when you doarr.indexOf( s._id )
it you are not searching on the fields_id
of each object but on the indices of each of the objects (0, 1, 2...) therefore it never finds the value for you and that is why for each iteration offoreach
it introduces the object into the array.I have added a function to your code (objectAlreadyContained) in which I directly compare the id
id
of each of the objects contained in the arrayarr
with the id of the object that we are comparing at that moment and, if it is not contained, add it to the array.You could use
.filter
,.some
and.test
to reduce code. The idea would be to filter all elements where any of the properties ('name', 'email', 'role') match the search.