const key = 'workplace';
const values = [ 'office', 'hotel' ];const result = arr.filter(function(n) {
return this.has(n[key]);
}, new Set(values));
// или
const result = values.flatMap(((grouped, n) => grouped[n] ?? []).bind(
null,
arr.reduce((acc, n) => ((acc[n[key]] = acc[n[key]] ?? []).push(n), acc), {})
));
// или
const result = [];
for (const n of arr) {
for (const m of values) {
if (m === n[key]) {
result.push(n);
break;
}
}
}
// или
const result = [];
for (let i = 0; i < arr.length; i++) {
if (~values.indexOf(arr[i][key])) {
result[result.length] = arr[i];
}
}
// или
const result = (function get(i, n = arr[i]) {
return n
? [].concat(values.includes(n[key]) ? n : [], get(-~i))
: [];
})(0);
#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');
});
const placeholders = [ 'hello, world!!', 'fuck the world', 'fuck everything' ];
const delay = 200;
const input = document.querySelector('input');function interval(arr, delay, callback) {
let i = -1;
return arr.length
? setInterval(() => callback(arr[i = -~i % arr.length]), delay)
: null;
}
const intervalId = interval(placeholders, delay, n => input.placeholder = n);
// хотим остановить, делаем так: clearInterval(intervalId);function interval(arr, delay, callback) {
let timeoutId = null;
arr.length && (function next(i) {
timeoutId = setTimeout(() => {
callback(arr[i]);
next((i + 1) % arr.length);
}, delay);
})(0);
return () => clearTimeout(timeoutId);
}
const stop = interval(
placeholders,
delay,
Element.prototype.setAttribute.bind(input, 'placeholder')
);
// хотим остановить, делаем так: stop();
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, ''),
};
}
const getVal = option =>
option.value;
// или
// option.getAttribute('value');
// option.attributes.value.value;const addText = (option, text) =>
option.text += text;
// или
// option.textContent = option.textContent.concat(text);
// option.innerText = `${option.innerText}${text}`;
// option.append(text);
// option.insertAdjacentText('beforeend', text);
// option.appendChild(document.createTextNode(text));
// option.insertBefore(new Text(text), null);const addValToText = option => addText(option, getVal(option));Array.prototype.forEach.call(select, addValToText);
// или
select.querySelectorAll('option').forEach(addValToText);
// или
for (const n of select) {
addValToText(n);
}
// или
for (let i = 0; i < select.options.length; i++) {
addValToText(select.options.item(i));
}
// или
(function add(i, n = select.children[i]) {
if (n) {
addValToText(n);
add(i + 1);
}
})(0);
// или
const add = n => n && (addValToText(n), add(n.nextElementSibling));
add(select.firstElementChild);
str.replace(/:$/, '')
// или
/(.*?):?$/.exec(str)[1]
// или
str.match(/[^:]+:[^:]+/)[0]
// или
str.split(':', 2).join(':')
// или
str.slice(0, str.slice(-1) === ':' ? -1 : void 0)
// или
str.substring(0, str.length - !!-~str.search(':$'))
$('.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)} %`),
});
});
let result = '';
for (const k in obj) {
if (obj.hasOwnProperty(k)) {
result += (result && '&') + k + '=' + obj[k];
}
}
// или
const result = Object.entries(obj).map(n => n.join('=')).join('&');
// или
const result = `${new URLSearchParams(obj)}`;
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], acc), {});function count(data, key = n => n) {
const counted = {};
for (const n of data) {
const k = key(n);
counted[k] = (counted[k] ?? 0) + 1;
}
return counted;
}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}count(Array(9).keys(), n => [ 'чётные', 'нечётные' ][n & 1]) // {чётные: 5, нечётные: 4}
#elem нового контента следует полностью перезаписывать его содержимое:document.querySelector('#elem').innerHTML = `
<table>${Array.from({ length: 2 }, (_, iRow) => `
<tr>${Array.from({ length: columns }, (_, iCol) => `
<td>${iRow + 1}.${iCol + 1}</td>`).join('')}
</tr>`).join('')}
</table>
`;const table = document.createElement('table');
table.insertRow();
table.insertRow();
document.querySelector('#elem').append(table);for (const n of table.rows) {
while (n.cells.length < columns) {
n.insertCell().textContent = `${-~n.rowIndex}.${n.cells.length}`;
}
while (n.cells.length > columns) {
n.lastElementChild.remove();
}
}