const key = 'workplace';
const values = [ 'office', 'hotel' ];
const result = arr.filter(n => values.includes(n[key]));
// или
const result = values.flatMap(function(n) {
return this[n] ?? [];
}, arr.reduce((acc, n) => ((acc[n[key]] = acc[n[key]] ?? []).push(n), acc), {}));
// или
const filter = (arr, key, values) =>
arr.filter(function(n) {
return this.has(n[key]);
}, new Set(values));
const result = filter(arr, key, values);
#list-case
вы назначаете обработчики клика всем существующим .img
и .show
, а не только свежесозданным. Если срабатывает два (или четыре, или шесть, или...) обработчика, которые выполняют toggleClass, то конечное состояние от начального отличаться не будет. Отсюда ваше кажущееся "не работает"..case
, делайте это один раз, используя делегирование:$('#list-case')
.on('click', '.img', function() {
$(this).closest('.case').remove();
})
.on('click', '.show', function() {
$(this).toggleClass('none').closest('.case').find('.case-bottom').toggleClass('invise');
});
function interval(arr, delay, callback) {
let index = -1;
return setInterval(() => {
index = (index + 1) % arr.length;
callback(arr[index]);
}, delay);
}
const intervalId = interval(
[ 'hello, world!!', 'fuck the world', 'fuck everything' ],
1000,
function(placeholder) {
this.placeholder = placeholder;
}.bind(document.querySelector('input'))
);
return false;
toggle дважды начинает срабатывать
const comparators = [
[ 'city', (itemVal, filterVal) => itemVal === filterVal ],
[ 'title', (itemVal, filterVal) => itemVal.includes(filterVal) ],
[ 'type', (itemVal, filterVal) => itemVal.includes(filterVal) ],
];
const filteredArr = arr.filter(n => comparators.every(([ k, f ]) => f(n[k], filter[k])));
document.querySelectorAll('.group-options__item').forEach(n => {
const input = (n.closest('.group-options') ?? n).querySelector('[data-prop]');
if (input) {
input.checked = true;
}
});
function getStrings(str) {
const str1 = str.match(/\(.+?\)/g)?.find(n => /\d/.test(n)) ?? '';
return {
str1: str1.slice(1, -1),
str2: str.replace(str1, ''),
};
}
str.replace(/:$/, '')
// или
str.match(/[^:]+:[^:]+/)[0]
// или
str.match(/[^:]+/g).slice(0, 2).join`:`
// или
str.split(':', 2).join(':')
// или
str.slice(0, str.length - (str.slice(-1) === ':'))
$('.progress__item').each(function() {
const $this = $(this);
const $progressBar = $this.find('.progress__bar');
const $value = $this.find('.progress__value');
const value = $progressBar.data('progress-value');
$progressBar.width(`${value}%`);
$({ value: 0 }).animate({
value,
}, {
duration: 1000,
step: val => $value.text(`${val.toFixed(1)} %`),
});
});
m => `<span style="background: red;">${m}</span>`
'<span style="background: red;">$&</span>'
const p = document.querySelector('.resultParagraph');
document.querySelector('.input').addEventListener('keypress', e => {
if (e.key === 'Enter') {
const regex = RegExp(e.target.value, 'gmi');
const replacement = '<span style="background: red;">$&</span>';
p.innerHTML = p.textContent.replace(regex, replacement);
}
});
const result = [...str].reduce((acc, n) => (acc[n] = (acc[n] ?? 0) + 1, acc), {});
const count = (data, key = n => n) =>
Array.prototype.reduce.call(data, (acc, n) => (
n = key(n),
acc[n] = -~acc[n],
acc
), {});
const result = count(str);
const nums = [ -Infinity, -1, 0, 0, 0, 0, 69, 187, 666 ];
console.log(count(nums, Math.sign)); // {0: 4, 1: 3, -1: 2}
<div data-country="USA">New York</div>
<div data-country="USA">Boston</div>
<div data-country="USA">Las Vegas</div>
<div data-country="Japan">Osaka</div>
<div data-country="Japan">Tokyo</div>
<div data-country="Japan">Kyoto</div>
<div data-country="Japan">Yokohama</div>
<div data-country="Germany">Munich</div>
<div data-country="Germany">Dresden</div>
const cities = document.querySelectorAll('[data-country]');
console.log(count(cities, n => n.dataset.country)); // {USA: 3, Japan: 4, Germany: 2}
$('#elem').html(`
<table>${[...Array(2)].map((n, iRow) => `
<tr>${[...Array(+columns)].map((m, iCol) => `
<td>${iRow + 1}.${iCol + 1}</td>`).join('')}
</tr>`).join('')}
</table>
`);
Как проверить, есть ли в массиве повторяющиеся элементы...
const hasDuplicates = arr.length > new Set(arr).size;
...и как записать эти элементы в новый массив...
// Получаем повторяющиеся элементы в единственном экземпляре
const duplicatedItemsUnique = Array.from(arr.reduce((acc, n) => (
acc[+acc[0].has(n)].add(n),
acc
), [ new Set, new Set ])[1]);
// Получаем все неуникальные элементы
const duplicatedItemsAll = arr.filter(function(n) {
return this.get(n) > 1;
}, arr.reduce((acc, n) => acc.set(n, -~acc.get(n)), new Map));
...или оставить только элементы которые повторяются?
arr.splice(0, arr.length, ...arr.filter(function(n) {
return this.get(n);
}, arr.reduce((acc, n) => acc.set(n, acc.has(n)), new Map)));
const containerSelector = '.lg-container';
const itemSelector = `${containerSelector} .lg-hotspot`;
const buttonSelector = `${itemSelector} .lg-hotspot__button`;
const activeClass = 'lg-hotspot--selected';
document.addEventListener('click', ({ target: t }) => {
const button = t.closest(buttonSelector);
const item = t.closest(itemSelector);
if (button) {
item.closest(containerSelector).querySelectorAll(itemSelector).forEach(n => {
n.classList[n === item ? 'toggle' : 'remove'](activeClass);
});
} else if (!item?.classList.contains(activeClass)) {
document.querySelectorAll(itemSelector).forEach(n => {
n.classList.remove(activeClass);
});
}
});
item.closest(containerSelector)
надо заменить на document
. return character === '...' ? '...' : character;
const replacements = {
'...': '...',
'...': '...',
...
};
const newCharacters = characters.map(n => replacements[n] || n);