$('#cityFilter').on('input', function() {
const value = this.value.toLowerCase();
$('#city-list .city')
.hide()
.filter((i, n) => $(n).text().toLowerCase().includes(value))
.show();
$('#city-list .state')
.hide()
.filter((i, n) => $(n).nextUntil('.state').is(':visible'))
.show();
});
document.querySelector('#cityFilter').addEventListener('input', e => {
const value = e.target.value.toLowerCase();
document.querySelectorAll('#city-list li').forEach(function(n) {
if (n.matches('.state')) {
this.splice(0, 2, n, true);
} else {
const hide = n.textContent.toLowerCase().indexOf(value) === -1;
this[1] &&= hide;
n.classList.toggle('hidden', hide);
if (!n.nextElementSibling?.matches('.city')) {
this[0].classList.toggle('hidden', this[1]);
}
}
}, [ null, true ]);
});
document.querySelectorAll('.col').forEach(n => {
n.querySelectorAll('a').forEach((m, i) => m.classList.toggle('d-none', !!i));
});
document.querySelectorAll('.col a').forEach(n => {
n.classList.toggle('d-none', !!n.previousElementSibling);
});
const filterSelector = '.js-filter';
const itemSelector = '.dfth__item';
const checkboxSelector = '.dfth__check:checked';
const labelSelector = '.dfth__label';
const resetSelector = '.dfth__reset';
const selectedSelector = '.js-type-result';
const defaultValue = 'ничего не выбрано';
const $filter = $(filterSelector).change(function() {
const selected = $(checkboxSelector, this)
.closest(itemSelector)
.find(labelSelector)
.get()
.map(n => $(n).text())
.join(', ');
$(selectedSelector, this).text(selected || defaultValue);
});
$filter.find(resetSelector).click(() => {
$filter.find(checkboxSelector).prop('checked', false);
$filter.trigger('change');
});
const filter = document.querySelector(filterSelector);
filter.addEventListener('change', ({ currentTarget: ct }) => {
const selected = Array
.from(
ct.querySelectorAll(checkboxSelector),
n => n.closest(itemSelector).querySelector(labelSelector).textContent)
.join(', ');
ct.querySelector(selectedSelector).textContent = selected || defaultValue;
});
filter.querySelector(resetSelector).addEventListener('click', () => {
filter.querySelectorAll(checkboxSelector).forEach(n => n.checked = false);
filter.dispatchEvent(new Event('change'));
});
const hasDuplicates = map.size > new Set(Array.from(map, n => n[1].id)).size;
const duplicates = Array
.from([...map].reduce((acc, [ , { id } ]) => acc.set(id, acc.has(id)), new Map))
.reduce((acc, n) => (n[1] && acc.push(n[0]), acc), []);
const count = Array
.from(map.values())
.reduce((acc, { id }) => acc.set(id, -~acc.get(id)), new Map);
const containerSelector = '.block-btn';
const itemSelector = `${containerSelector} [data-cost]`;
const activeClass = 'active';
const onClick = ({ currentTarget: t }) => t
.closest(containerSelector)
.querySelectorAll(itemSelector)
.forEach(n => n.classList.toggle(activeClass, n === t));
document.querySelectorAll(itemSelector).forEach(n => {
n.addEventListener('click', onClick);
});
for (const n of document.querySelectorAll(containerSelector)) {
n.addEventListener('click', onClick);
}
function onClick(e) {
const item = e.target.closest(itemSelector);
if (item) {
this.querySelector(`.${activeClass}`)?.classList.remove(activeClass);
item.classList.add(activeClass);
}
}
document.addEventListener('click', ({ target: t }) => t
.closest(itemSelector)
?.closest(containerSelector)
.querySelectorAll(itemSelector)
.forEach(n => n.classList.toggle(activeClass, n.contains(t)))
);
const delimiter = str.match(/\D/)[0];
// или
const delimiter = str[str.search(/\D/)];
// или
const [ delimiter ] = str.replace(/^\d+/, '');
// или
const delimiter = Array.prototype.find.call(str, n => Number.isNaN(+n));
// или
const delimiter = [...str].filter(n => !'0123456789'.includes(n)).shift();
const parent = document.querySelector('.container');
const className = 'green';
const startFrom = 4;
parent
.querySelectorAll(`:scope > :nth-child(n + ${startFrom + 1})`)
.forEach(n => n.classList.add(className));
// или
for (const n of Array.prototype.slice.call(parent.children, startFrom)) {
n.classList.add(className);
}
// или
for (let el = parent.children[startFrom]; el; el = el.nextElementSibling) {
el.classList.add(className);
}
// или, также удаляем класс (если вдруг есть) у тех, кому он не должен быть добавлен
for (let i = 0; i < parent.children.length; i++) {
parent.children[i].classList.toggle(className, i >= startFrom);
}
function createRandomArr(length, min, max) {
if (length > max - min + 1) {
throw 'такого массива быть не может';
}
const values = new Set;
for (; values.size < length; values.add(min + Math.random() * (max - min + 1) | 0)) ;
return [...values];
}
const createRandomArr = (length, min, max) => Array
.from({ length }, function() {
return this.splice(Math.random() * this.length | 0, 1);
}, Array.from({ length: max - min + 1 }, (n, i) => i + min))
.flat();
function createRandomArr(length, min, max) {
const arr = Array.from({ length: max - min + 1 }, (n, i) => min + i);
for (let i = arr.length; --i > 0;) {
const j = Math.random() * (i + 1) | 0;
[ arr[i], arr[j] ] = [ arr[j], arr[i] ];
}
return arr.slice(0, length);
}
const values = [ id, sum, system, date ];
.payment.innerHTML = values.map(n => `<td>${n}</td>`).join('');
// или
values.forEach(n => payment.insertCell().textContent = n);
// или
payment.append(...values.map(n => {
const td = document.createElement('td');
td.innerText = n;
return td;
}));
- function createPayment({id, sum, system, date}) {
+ function createPayment(data) {
- const values = [ id, sum, system, date ];
+ const keys = [ 'id', 'sum', 'system', 'date' ];
- values.forEach(n => payment.insertCell().textContent = n);
+ keys.forEach(n => payment.insertCell().textContent = data[n]);
const propsCount = 3;
.const newObj = Object.fromEntries(Object
.entries(obj)
.sort((a, b) => a[1] - b[1])
.slice(-propsCount)
);
Object
.entries(obj)
.sort((a, b) => b[1] - a[1])
.slice(propsCount)
.forEach(n => delete obj[n[0]]);
str.match(/(?<=>)\d+/g) ?? []
// или
str.match(/>\d+/g)?.map(n => n.slice(1)) ?? []
// или
Array.from(str.matchAll(/>(\d+)/g), n => n[1])
''.concat(...Array.from(str, n => n.repeat(2)))
// или
str.replace(/./g, '$&$&')
// или
str.replace(/./g, m => Array(3).join(m))
// или
str.replace(/(?=.)/g, (m, i) => str[i])
// или
[...str].flatMap(n => Array(2).fill(n)).join('')
// или
[].map.call(str, n => `${n}${n}`).join``
// или
str.split('').reduce((acc, n) => acc + n + n, '')
const averageAge = arr.reduce((acc, n) => acc + n.age, 0) / arr.length;
function avg(data, key = n => n) {
const getVal = key instanceof Function ? key : n => n[key];
let sum = 0;
let count = 0;
for (const n of data) {
sum += getVal(n);
count += 1;
}
return sum / count;
}
const averageAge = avg(arr, 'age');
.avg(Array(10).keys()) // 4.5
avg('12345', Number) // 3
avg(document.images, n => n.width) // сами посмотрите, сколько тут получится
arr.reduce((acc, n, i) => (
(!i || n === 1) && acc.push([]),
acc[acc.length - 1].push(n),
acc
), [])
const index = arr.reduce((min, n, i, a) => a[min]?.length <= n.length ? min : i, -1);
if (index !== -1) {
arr[index] = arr[index][0].toUpperCase() + arr[index].slice(1);
}
const [ indexes ] = arr.reduce((min, n, i) => (
n.length < min[1] && (min = [ [], n.length ]),
n.length === min[1] && min[0].push(i),
min
), [ [], Infinity ]);
indexes.forEach(n => arr[n] = arr[n].replace(/./, m => m.toUpperCase()));
const date = new Date(str.replace(/\S+/, m => m.split('.').reverse().join('-')));
const date = new Date(str.replace(/(\d+)\.(\d+)\.(\d+)/, '$3-$2-$1'));
const [ day, month, year, hours, minutes, seconds ] = str.split(/\D/);
const date = new Date(year, month - 1, day, hours, minutes, seconds);
const date = dayjs(str, 'DD.MM.YYYY HH:mm:ss').toDate();
function sort([...arr]) {
const max = arr.reduce((max, n) => max?.population > n.population ? max : n, null);
return arr.sort((a, b) => a === max ? -1 : b === max ? 1 : a.city.localeCompare(b.city));
}
const className = 'model';
const elements = document.querySelectorAll(`.${className}`);
// или
const elements = document.getElementsByClassName(className);
const getText = el => el.textContent;
// или
const getText = el => el.innerText;
// или (т.к. вложенных элементов нет, это тоже сработает как надо)
const getText = el => el.innerHTML;
const result = Array.from(elements, getText).join(', ');
// или
const result = ''.concat(...[...elements].flatMap((n, i) => (
n = getText(n),
i ? [ ', ', n ] : n
)));
// или
const result = Array.prototype.reduce.call(
elements,
(acc, n, i) => acc + (i ? ', ' : '') + getText(n),
''
);