const li = document.querySelectorAll('li');
li.forEach(n => n.addEventListener('click', onClick));
function onClick(e) {
e.preventDefault();
li.forEach(n => n.classList.toggle('active', n === this));
const href = this.querySelector('a').getAttribute('href');
document.querySelector(href).scrollIntoView({
behavior: 'smooth',
});
}
const text = 'hello, world!!';
const max = 20;
let len = 0;
for (const p of document.querySelectorAll('p')) {
len += p.textContent.length;
if (len >= max) {
p.insertAdjacentText('afterend', text);
break;
}
}
function tableString(arr, numCols, colSpacing = 3) {
const numRows = Math.ceil(arr.length / numCols);
const rows = Array.from(
{ length: numRows },
(n, i) => arr.slice(i * numCols, (i + 1) * numCols)
);
const widths = Array.from(
{ length: numCols },
(n, i) => Math.max(...rows.map(m => (m[i] ?? '').length))
);
return rows
.map(n => n.map((m, i) => m.padEnd(colSpacing + widths[i], ' ')).join(''))
.join('\n');
}
const arr = [
'11111', '22222222', '33333333', '444', '11', '222', '3333',
'4444444', '11111111', '222222', '33333333', '4', '1',
'2222222222', '3', '44444444444444',
];
console.log(tableString(arr, 4));
console.log(tableString(arr, 3));
console.log(tableString(arr, 3, 8));
/*
* надеюсь, хотя бы вместо "по всему документу" вы сумеете подобрать
* какой-нибудь вменяемый селектор, чтобы не проверять реально всё,
* а только те элементы, где ваш "undefined" действительно может случиться
*/
document.querySelectorAll('*').forEach(n => {
const text = n.innerText?.trim();
if (text === 'undefined') {
n.hidden = true;
}
});
const arr = str.split(/(?<=[A-Z]), /);
// или
const arr = str.match(/[^,\s][^,]*, [^,]+/g) ?? [];
// или
const arr = str
.split(', ')
.reduce((acc, n, i) => (
(i & 1) || acc.push([]),
acc[acc.length - 1].push(n),
acc
), [])
.map(n => n.join(', '));
.hidden {
display: none;
}
const filter = document.querySelector('.filter');
filter.addEventListener('change', function() {
document.querySelectorAll('.cart-product').forEach(function(n) {
n.classList.toggle('hidden', this.length && !this.includes(n.dataset.category));
}, Array.from(this.querySelectorAll(':checked'), n => n.dataset.filter));
});
filter.dispatchEvent(new Event('change'));
function showDotsCountInPolygon(e) {
const dotsCountInPolygon = dots
.filter(n => google.maps.geometry.poly.containsLocation(new google.maps.LatLng(n), this))
.length;
infoWindow.setContent(`Точек в полигоне: ${dotsCountInPolygon}`);
infoWindow.setPosition(e.latLng);
infoWindow.open(map);
}
polygon.addListener('click', showDotsCountInPolygon);
function createTreeData(arr, idProp, parentProp) {
const tree = Object.fromEntries(arr.map(n => [ n[idProp], { ...n, children: [] } ]));
return Object.values(tree).filter(n => !tree[n[parentProp]]?.children.push(n));
}
const createTreeHTML = data =>
Array.isArray(data) && data.length
? `<ul>${data.map(n => `
<li>
${n.name}
${createTreeHTML(n.children)}
</li>`).join('')}
</ul>`
: '';
const treeData = createTreeData(data, 'id', 'parent_id');
const treeHTML = createTreeHTML(treeData);
treeContainerElement.innerHTML = treeHTML;
const newArr = [...Array(num)].reduce((acc, n, i) => (
acc[(index + i) % acc.length]++,
acc
), [...arr]);
// или
const newArr = arr.map(function(n, i, a) {
return n + this[0] + (((i - index) % a.length + a.length) % a.length < this[1]);
}, [ num / arr.length | 0, num % arr.length ]);
for (let i = num; i-- > 0; arr[(index + i) % arr.length]++) ;
// или
(function xxx(i) {
if (--i >= 0) {
arr[(index + i) % arr.length]++;
xxx(i);
}
})(num);
В чем моя ошибка?
const sum = val =>
val instanceof Object
? Object.values(val).reduce((acc, n) => acc + sum(n), 0)
: val;
console.log(sum(obj));
.faq__answer
не растягивал родительский элемент и, соответственно, не перемещал лежащие ниже .faq__question
, надо задать ему position: absolute
. И ещё z-index
побольше, чем у .faq__quest
, чтобы не прятался за ними.visibility
- так, чтобы элемент, будучи скрытым, продолжал занимать отведённое ему место.function onChange() {
document.querySelector('селектор элемента для вывода результата проверки').innerText = [
// здесь массив селекторов вида
// input[имя_атрибута1="значение1"][имя_атрибута2="значение2"]:checked
].every(n => document.querySelector(n))
? 'какой-то текст'
: 'какой-то другой текст';
}
onChange();
document.addEventListener('change', e => {
if (e.target.matches('input[type="radio"]')) {
onChange();
}
});
Object.entries(str.split('').reduce((acc, n) => (acc[n] = (acc[n] ?? 0) + 1, acc), {}))
[...[...str].reduce((acc, n) => acc.set(n, -~acc.get(n)), new Map)]
Object.values(str).sort().join('').match(/(.)\1*/g)?.map(n => [ n[0], n.length ]) ?? []
Array.from(new Set(str), n => [ n, str.split(n).length - 1 ])
const result = Object.values(runs.reduce(
(acc, n) => (acc[n.projectId]?.description.push(n), acc),
Object.fromEntries(projects.map(n => [ n.id, { ...n, description: [] } ]))
));
const result = projects.map(function(n) {
return {
...n,
description: this[n.id] ?? [],
};
}, runs.reduce((acc, n) => ((acc[n.projectId] = acc[n.projectId] ?? []).push(n), acc), {}));
const result = projects.map(n => ({
...n,
description: runs.filter(m => m.projectId === n.id),
}));
users.sort((a, b) => (a.age ?? Infinity) - (b.age ?? Infinity));
const sortedUsers = Object
.values(users.reduce((acc, n) => ((acc[n.age] = acc[n.age] ?? []).push(n), acc), {}))
.flat();
// или
const sorted = (arr, key) => arr
.map(n => [ n, key(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);
const sortedUsers = sorted(users, n => n.age ?? Infinity);