JavaScript
- 49 ответов
- 0 вопросов
49
Вклад в тег
function filter(array = [], filters = {}) {
const keys = Object.keys(filters).filter(key => filters.hasOwnProperty(key));
return array.filter(elem => {
const commonKeys = keys.filter(key => elem.hasOwnProperty(key));
return commonKeys.reduce((flag, key) => (flag && filters[key].includes(elem[key])), true);
});
}
filters
кладёте допустимые значения по соответствующим ключам. Например:const products = [
{country: 'Russia', img: 'link.img', genre: 'Comedy', name: 'Вишнёвый сад'},
{country: 'France', img: 'link.img', genre: 'Novel', name: 'Oberman'},
{country: 'Italy', img: 'link.img', genre: 'Adventures', name: 'Il cimitero di Praga'},
{country: 'USA', img: 'link.img', genre: 'Comedy', name: 'The Ransom of Red Chief'}
];
const filters = {
country: ['Russia', 'Italy', 'France'],
genre: ['Comedy', 'Novel']
};
const filteredProducts = filter(products, filters);
function format(str) {
const s = str.length;
const chars = str.split('');
const strWithSpaces = chars.reduceRight((acc, char, i) => {
const spaceOrNothing = ((((s - i) % 3) === 0) ? ' ' : '');
return (spaceOrNothing + char + acc);
}, '');
return ((strWithSpaces[0] === ' ') ? strWithSpaces.slice(1) : strWithSpaces);
}