Búsqueda Fuzzy sobre un Array Object en Javascript con Underscore

Germán Peraferrer
Jun 6, 2015 · 3 min read
/**
* Regular Expresion IndexOf for Arrays
* This little addition to the Array prototype will
* iterate over array and return the index of the
* first element which matches the provided regular
* expresion.
*
* Note: This will not match on objects.
*
* @param {RegEx} rx The regular expression to
* test with. E.g. /-ba/gim
* @return {number} -1 means not found
*/
Array.prototype.regIndexOf = function (rx) {
for (var i in this) {
if (this[i].toString().match(rx)) {
return i;
}
}

return -1;
};
var arr = ['German', 'Dario', 'Guadalupe', 'Sofia'];arr.regIndexOf(/germ/i);
/**
* Fuzzy Search in a Collection
*
* @param search Regex that represents what is going
* to be searched
*
* @return {Array} ArrayObject with an object of what
* we are looking for
*/
Array.prototype.fuzzy = function(search) {
var _return = [];
/**
* Runs deep the object, to his last nodes and
* returns an array with all the values.
*
* @param object Object that is going to be
* analized
* @return {Array} with all the values of the
* object at the same level
*/
var recursive = function(object) {
return _.map(object, function (obj, key) {
if (typeof obj !== ‘object’) {
return obj.toString();
} else {
return recursive(obj);
}
});
};
// Search inside the flatten array which was
// returned by recursive
_.each(recursive(this), function (obj, key) {
if (obj.regIndexOf(search) > -1) {
_return.push(this[key]);
}
}, this);
return _return;
};
var collection = [{
name: 'German',
language: [{
name: 'Javascript',
expertise: 8
}, {
name: 'Node.js',
expertise: 7
}]
}, {
name: 'Diego',
language: [{
name: 'HTML',
expertise: 9
}, {
name: 'CSS',
expertise: 10
}]
}];
// Busca la palabra "node" insensitive
collection.fuzzy(/node/i);
// También podemos buscar un texto
collection.fuzzy('Node');

    Germán Peraferrer

    Written by

    Ingenioso, nunca pidas permiso y recordá que lo imposible esta en la mente de los cómodos !!

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade