const className = 'text';.{ старый_текст: новый_текст }:const months = Object.fromEntries(Array.from({ length: 12 }, (n, i) => {
const d = new Date(0, i);
return [
d.toLocaleString('en-US', { month: 'long' }),
d.toLocaleString('ru-RU', { month: 'long' }).replace(/./, m => m.toUpperCase()),
];
}));$('.' + className).text((i, text) => months[text.trim()]);
// или
document.querySelectorAll(`.${className}`).forEach(n => {
const key = n.innerText;
if (months.hasOwnProperty(key)) {
n.innerText = months[key];
}
});
// или
for (const n of document.getElementsByClassName(className)) {
n.textContent = months[n.textContent.trim()] ?? n.textContent;
}
document.querySelector('table').addEventListener('input', e => {
const tr = e.target.closest('tr');
const price = parseInt(tr.querySelector('.price').innerText);
const value = e.target.value;
tr.querySelector('.item_result').innerText = value * price;
});
function groupNames(arr) {
const tree = Object.fromEntries(arr.map(n => [ n.categoryId, { ...n, children: [] } ]));
const values = Object.values(tree);
const getNames = ({ name, children }) => children.length
? children.reduce((acc, n) => (
acc.push(...getNames(n).map(m => [ name, ...m ])),
acc
), [])
: [ [ name ] ];
values.forEach(n => tree[n.parentCategoryId]?.children.push(n));
return values
.filter(n => !n.parentCategoryId)
.flatMap(n => getNames(n).map(n => n.join(' - ')));
}
forEach и for...of. Откройте документацию и разберитесь.forEach нельзя прервать (throw не в счёт), в то время как в теле for...of можно использовать break и return (да, в forEach тоже можно использовать return, но эффект будет не тот - уход на следующую итерацию, т.е., то же, что и continue для for...of).forEach можно назначать контекст выполнения (через второй параметр, коллбек при этом не должен быть стрелочной функцией).forEach отложить запуск следующей итерации до окончания выполнения асинхронных операций, запущенных в текущей итерации. В случае for...of можно добавить async в объявление функции, внутри которой он находится, и использовать await.Symbol.iterator, то это ещё не означает, что и forEach там тоже присутствует. Впрочем, тут могут быть (не всегда), варианты одолжить чужой forEach:Array.prototype.forEach.call('ABC', alert);
NodeList.prototype.forEach.call(document.scripts, console.log);
$('.button').click(function() {
const val = +$('.value').text((i, text) => +text + 1).text();
$('.item')
.removeClass('xxx')
.filter((i, el) => +$(el).text() <= val)
.sort((a, b) => $(a).text() - $(b).text())
.last()
.addClass('xxx');
});document.querySelector('.button').addEventListener('click', () => {
const val = ++document.querySelector('.value').innerText;
const items = Array.from(document.querySelectorAll('.item'), n => [ n, +n.innerText ]);
const max = items.reduce((max, n) => n[1] <= val && n[1] > max ? n[1] : max, -Infinity);
items.forEach(n => n[0].classList.toggle('xxx', n[1] === max));
});
const parseValue = str => {
const values = str.match(/[^\s,]+/g) ?? [ null ];
return values.length > 1 ? values : values[0];
};
const parseStyleStr = str =>
str.split(';').reduce((acc, n) => {
const [ k, v ] = n.split(':').map(n => n.trim());
if (k && v) {
const f = [...v.matchAll(/([\w]+?)\((.+?)\)/g)];
acc[k] = f.length
? Object.fromEntries(f.map(n => [ n[1], parseValue(n[2]) ]))
: parseValue(v);
}
return acc;
}, {});
Хорошо бы если на чистом css
но и js тоже можно
document.addEventListener('click', ({ target: { tagName, parentNode: p } }) => {
if (tagName === 'SUMMARY') {
document.querySelectorAll('details').forEach(n => n.open = n.open && n === p);
}
});
// или
const details = document.querySelectorAll('details');
const onClick = e => details.forEach(n => n.open = n.open && n === e.target.parentNode);
details.forEach(n => n.children[0].addEventListener('click', onClick));
const obj = arr.find(n => n.id === newObj.id);
if (obj) {
obj.counter++;
} else {
arr.push({ ...newObj, counter: 1 });
}
on на one. Но что если запрос окажется неудачным? Наверное, надо оставить пользователю возможность повторить действие. Вон, у вас там класс добавляется - так проверяйте его наличие, если уже есть, ничего делать не надо; также добавьте обработку неудавшихся запросов, там надо будет класс снять.
const getReversedPaths = (arr, path = []) =>
arr.reduce((acc, { childItems, ...item }) => {
path.push(item);
if (childItems) {
acc.push(...getReversedPaths(childItems, path));
} else {
acc.push(path.length > 1
? path.map(({ packingLevel }, i, a) => ({ ...a[a.length - i - 1], packingLevel }))
: [ path[0] ]
);
}
path.pop();
return acc;
}, []);const reverseThere = arr =>
getReversedPaths(arr).map(n =>
n.reduceRight((child, parent) => ({ ...parent, childItems: [ child ] }))
);const reverseBackAgain = arr =>
(function createTree(arr) {
return Object.values(arr.reduce((acc, [ head, ...tail ]) => {
if (tail.length) {
(acc[head.name] = acc[head.name] ?? { ...head, childItems: [] }).childItems.push(tail);
} else {
acc[head.name] = head;
}
return acc;
}, {})).map(n => (n.childItems && (n.childItems = createTree(n.childItems)), n));
})(getReversedPaths(arr));
const newArr2 = arr2.filter(n => arr1.some(m => m === n.name));
// или
const obj2 = arr2.reduce((acc, n) => (
(acc[n.name] = acc[n.name] ?? []).push(n),
acc
), {});
const newArr2 = arr1.flatMap(n => obj2[n] ?? []);
// или
const newArr2 = [];
for (const n of arr2) {
for (const m of arr1) {
if (m === n.name) {
newArr2.push(n);
break;
}
}
}arr2.reduceRight((_, n, i, a) => ~arr1.indexOf(n.name) || a.splice(i, 1), null);
// или
arr2.splice(0, arr2.length, ...arr2.filter(function(n) {
return this.has(n.name);
}, new Set(arr1)));
// или
arr2.length -= arr2.reduce((acc, n, i, a) => (
a[i - acc] = n,
acc + !arr1.includes(n.name)
), 0);
<select>
<option value="" hidden>здесь ваше описание</option>
...select.innerHTML = '<option value="" hidden>...</option>' + select.innerHTML;select.insertAdjacentHTML('afterbegin', '<option value="" hidden>...</option>');const option = document.createElement('option');
option.value = '';
option.hidden = true;
option.innerText = '...';
select.prepend(option);const option = new Option('...', '');
option.style.display = 'none';
select.insertBefore(option, select.firstElementChild);
<div id="items"></div>document.querySelector('.map__filters').addEventListener('change', function() {
const values = Array.from(
this.querySelectorAll('.map__checkbox:checked'),
n => n.value
);
const filtered = values.length
? data.filter(n => values.every(m => n.features.includes(m)))
: [];
document.querySelector('#items').innerHTML = filtered
.map(n => `<div>${JSON.stringify(n, null, 2)}</div>`)
.join('');
});
function filter(obj, key, f) {
const keys = Object.keys(obj);
return (obj[key] || []).reduce((acc, n, i) => (
f(n) && keys.forEach(k => acc[k].push(obj[k][i])),
acc
), keys.reduce((acc, k) => (acc[k] = [], acc), {}));
}
const result = filter(obj, 'years', n => 2012 <= n && n <= 2014);function filter(obj, f) {
const keys = Object.keys(obj);
const length = keys.length && obj[keys[0]].length;
const result = Object.fromEntries(keys.map(k => [ k, [] ]));
for (let i = 0; i < length; i++) {
if (f(i, obj)) {
keys.forEach(k => result[k].push(obj[k][i]));
}
}
return result;
}
const result = filter(obj, (i, { years: { [i]: n } }) => 2012 <= n && n <= 2014);