Skip to content

Instantly share code, notes, and snippets.

@santospatrick
Last active October 2, 2018 13:52
Show Gist options
  • Save santospatrick/ede002fbcaff0c6533e7b643936ff7d6 to your computer and use it in GitHub Desktop.
Save santospatrick/ede002fbcaff0c6533e7b643936ff7d6 to your computer and use it in GitHub Desktop.
Filter array of objects by any attribute and return a new filtered array
// ES6
import removeAccents from 'remove-accents';
/**
* Filter {@link list} based on any attribute by {@link searchString}
* and return a new one
* @param {string} searchString
* @param {array<*>} list
* @returns {array<*>} new filtered list
*/
const filterListByString = (searchString = '', list = []) => {
// in case list is falsy
if (!list) return [];
// in case searchString is falsy
if (!searchString) return list;
return list.filter(item =>
Object.values(item).some((property = '') => {
const itemAttribute = removeAccents(
property
.toString()
.toLowerCase()
.split(' ')
.join(''),
);
return itemAttribute.includes(
removeAccents(
searchString
.toString()
.toLowerCase()
.split(' ')
.join(''),
),
);
}),
);
};
// ES5
/**
* Filter {@link list} based on any attribute by {@link searchString}
* and return a new one
* @param {string} searchString
* @param {array<*>} list
* @returns {array<*>} new filtered list
*/
function filterListByString(searchString, list) {
// in case list is falsy
var listToFilter = list || [];
// in case searchString is falsy
var stringToSearch = searchString || '';
if (!stringToSearch) return listToFilter;
return listToFilter.filter(function(item) {
return Object.values(item).some(function(property) {
var propertyToSearch = property || '';
var itemAttribute = removeAccents(
propertyToSearch
.toString()
.toLowerCase()
.split(' ')
.join('')
);
return itemAttribute.includes(
removeAccents(
stringToSearch
.toString()
.toLowerCase()
.split(' ')
.join('')
),
);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment