const isSumEven = arr => arr.reduce((p, c) => p ^ c, 1) & 1;
// или
const isSumEven = arr => !(arr.filter(n => n % 2).length % 2);
// или
const isSumEven = arr => Number.isInteger(arr.reduce((acc, n) => acc + n, 0) / 2);
// или
const isSumEven = arr => /[02468]$/.test(eval(arr.join('+')) ?? 0);const result = arr.filter(isSumEven);.
function split(arr, numParts) {
const partSize = arr.length / numParts | 0;
return Array
.from({ length: numParts }, (n, i) => i * partSize)
.map((n, i, a) => arr.slice(n, a[i + 1]));
}function split(arr, numParts) {
const partSize = arr.length / numParts | 0;
const numLooseItems = arr.length % numParts;
return Array.from(
{ length: numParts },
function(_, i) {
return arr.slice(this(i), this(i + 1));
},
i => i * partSize + Math.min(i, numLooseItems)
);
}
coords.reduce((acc, n, i, a) => (
acc.push(n),
(n.line !== a[i + 1]?.line) && acc.push({ ...n, value: 0 }),
acc
), [])coords.flatMap((n, i, a) =>
i === ~-a.length || n.line !== a[-~i].line
? [ n, { ...n, value: 0 } ]
: n
)
const data = Array.prototype.reduce.call(
document.querySelector('form').elements,
(acc, { name, value }) => (
name.match(/\w+/g).reduce((p, c, i, a) =>
p[c] ??= (-~i < a.length ? {} : value)
, acc),
acc
),
{}
);Для
<input type="text" name="iuowye[rrr][]" value="1"> <input type="text" name="iuowye[rrr][]" value="2"> <input type="text" name="iuowye[rrr][]" value="3">
работать не будет.
const data = Array
.from(document.querySelectorAll('form [name]'))
.reduce((acc, n) => {
const keys = n.name.match(/\w+|\[\w*\]/g).map(n => n.replace(/^\[|\]$/g, ''));
const key = keys.pop();
const isArr = !key;
const values = keys.reduce((p, c, i, a) => {
return p[c] ??= (i === a.length - 1 && isArr ? [] : {});
}, acc);
values[isArr ? values.length : key] = n.value;
return acc;
}, {});
function sum(...v1) {
const s = v1.reduce((acc, n) => acc + n, 0);
const f = (...v2) => v2.length ? sum(...v2, s) : s;
return v1.length ? f : s;
}
const selector = '.text';
const regex = /@(\w+)/g;
const replacement = '<a href="https://site.com/$1">$&</a>';
const replace = str => str.replace(regex, replacement);$(selector).html((i, html) => replace(html));
// или
document.querySelectorAll(selector).forEach(n => {
n.innerHTML = replace(n.innerText);
});
return [...el].map((n) => new Select(n));Select на this.constructor.
const checkedTexts = (el, selector) =>
Array.from(el.querySelectorAll(`${selector}:checked`), n => n.parentNode.innerText);
const propertyText = (el, selector) =>
el.querySelector(selector).innerText.split(': ')[1];
document.querySelector('.container-filter').addEventListener('input', function() {
const maxPrice = parseInt(this.querySelector('.range').value);
const brands = checkedTexts(this, '.input');
const years = checkedTexts(this, '.input-date');
document.querySelectorAll('.device .laptop').forEach(n => {
const price = parseInt(propertyText(n, '.laptop-price'));
const brand = propertyText(n, '.laptop-name');
const year = propertyText(n, '.laptop-year');
n.style.display = (
(maxPrice >= price) &&
(!brands.length || brands.includes(brand)) &&
(!years.length || years.includes(year))
)
? 'block'
: 'none';
});
});
const newStr = str
.split(' ')
.map(function([...word]) {
const sorted = word.filter(this).sort((a, b) => b.localeCompare(a));
return word.map(n => this(n) ? sorted.pop() : n).join('');
}, RegExp.prototype.test.bind(/[a-z]/i))
.join(' ');
str.replace(/(\d{2})(\d{2})/, '$1.$2.')
// или
str.replace(/(?=\d{4}$|\d{6}$)/g, '.')
// или
str.match(/(..)(..)(.+)/).slice(1).join('.')
// или
[ 0, 2, 4 ].map((n, i, a) => str.slice(n, a[i + 1])).join`.`
// или
[...str].reduce((acc, n, i) => acc + n + ([ ,'.',,'.' ][i] || ''))
// или
''.concat(...Array.from(str, (n, i) => '24'.includes(i) ? `.${n}` : n))
const buttons = document.querySelector('.content');
const blocks = document.querySelector('.wrap');
const key = 'block';
const attr = `data-${key}`;
const attrSelector = `[${attr}]`;buttons.addEventListener('click', e => {
const button = e.target.closest(attrSelector);
if (button) {
const value = button.dataset[key];
console.log(blocks.querySelectorAll(`[${attr}="${value}"]`).length);
}
});const onClick = ({ currentTarget: { attributes: { [attr]: { value } } } }) =>
console.log(Array.prototype.reduce.call(
blocks.children,
(acc, n) => acc + (n.getAttribute(attr) === value),
0
));
for (const n of buttons.children) {
n.addEventListener('click', onClick);
}
document.querySelector('table').addEventListener('click', ({ target: t }) => {
if (t.classList.contains('save_order')) {
const tr = t.closest('tr');
console.log(tr);
}
// или
if (t.matches('.save_order')) {
let tr = t;
while ((tr = tr.parentNode).tagName !== 'TR') ;
console.log(tr);
}
});
arr.pop();
// или
arr.length -= !!arr.length;
// или
arr.splice(-1);const count = сколько надо удалить;):for (let i = count; --i >= 0 && arr.length; arr.pop()) ;
// или
arr.length -= Math.max(0, Math.min(arr.length, count));
// или
count > 0 && arr.splice(-count);
document.addEventListener('input', ({ target: t }) => {
if (t.classList.contains('rating__value')) {
const value = +t.value;
t.closest('.item-rating').querySelector('.rating__dynamic').innerHTML = Array
.from({ length: 5 }, (n, i) => `<span class="char">${'☆★'[+(value > i)]}</span>`)
.join('');
}
});
document.querySelectorAll('.rating__value').forEach(n => {
n.dispatchEvent(new Event('input', { bubbles: true }));
});for (const n of document.getElementsByClassName('rating__value')) {
n.previousElementSibling.innerHTML = '<span class="char"></span>'.repeat(5);
n.addEventListener('input', onRatingInput);
onRatingInput.call(n);
}
function onRatingInput() {
const value = this.value | 0;
const stars = this.previousElementSibling.children;
for (let i = 0; i < stars.length; i++) {
stars[i].innerText = value > i ? '★' : '☆';
}
}
const listTag = 'ul';
const listClass = 'list';
const itemTag = 'li';
const itemClass = 'item';
const activeClass = 'active';const list = document.createElement(listTag);
const items = arr.map(function(n) {
const item = document.createElement(itemTag);
item.textContent = n.text;
item.classList.add(itemClass);
item.addEventListener('click', this);
return item;
}, function() {
list.style.setProperty('background-image', `url(${arr[items.indexOf(this)].url})`);
items.forEach(n => n.classList.toggle(activeClass, n === this));
});
list.classList.add(listClass);
list.append(...items);
document.body.append(list);
items[0].click();document.body.insertAdjacentHTML('beforeend', `
<${listTag} class="${listClass}">${arr.map(({ url, text }) => `
<${itemTag} class="${itemClass}" data-url="${url}">${text}</${itemTag}>`).join``}
</${listTag}>
`);
const list = document.body.lastElementChild;
list.addEventListener('click', ({ target: t }) => {
if (t = t.closest(`${itemTag}.${itemClass}`)) {
list.style.backgroundImage = `url(${t.dataset.url})`;
list.querySelector(`.${activeClass}`)?.classList.remove(activeClass);
t.classList.add(activeClass);
}
});
list.children[0].dispatchEvent(new Event('click', { bubbles: true }));
const sorted = (arr, key) => arr
.map(n => [ key(n), n ])
.sort(([a], [b]) => a < b ? -1 : +(a > b))
.map(n => n[1]);const sortedArr = sorted(
arr,
n => new Date(n.date.replace(/(\d+)\.(\d+)\.(\d+)/, '$3-$2-$1'))
);
// или
const sortedArr = sorted(
arr,
n => n.date.replace(/[^T]+/, m => m.split('.').reverse().join(''))
);