g
на самом деле отсутствует. Смотрите внимательнее, куда вы его попытались вписать. str.match(/(?<=\. ).+(?= \(%\))/)[0]
// или
str.replace(/^.*?\. | \(%\).*$/g, '')
// или
str.split('. ').pop().split(' (%)').shift()
this.getRandomZ() не вычисляется
const getRandomPolynom = () => {
const [ A, B, C, D ] = Array.from({ length: 4 }, this.getRandomZ);
return x => A * x ** 4 + B * x ** 3 - C * x ** 2 - D * x + 10;
};
const wrapper = document.querySelector('.wrap');
const html = '<div class="item active">5</div>';
const last = wrapper.lastElementChild;
// или
const last = wrapper.querySelector(':scope > :last-child');
// или
const last = wrapper.children[wrapper.children.length - 1];
// или
const [ last ] = Array.prototype.slice.call(wrapper.children, -1);
last.insertAdjacentHTML('beforebegin', html);
// или
last.before(...new DOMParser().parseFromString(html, 'text/html').body.childNodes);
// или
wrapper.insertBefore(document.createRange().createContextualFragment(html), last);
// или
last.outerHTML = html + last.outerHTML;
const containerSelector = '.card';
const selectSelector = `${containerSelector} select`;
const dataAttr = 'name';
$(selectSelector).change(function() {
$(this)
.closest(containerSelector)
.find(`[data-${dataAttr}]`)
.hide()
.filter(`[data-${dataAttr}="${this.value}"]`)
.show();
}).val(defaultValueSelected).trigger('change');
// или
const selects = document.querySelectorAll(selectSelector);
const onChange = ({ target: t }) => t
.closest(containerSelector)
.querySelectorAll(`[data-${dataAttr}]`)
.forEach(n => n.style.display = t.value === n.dataset[dataAttr] ? 'block' : 'none');
selects.forEach(n => {
n.value = defaultValueSelected;
n.addEventListener('change', onChange);
n.dispatchEvent(new Event('change'));
});
const result = Object.values(arr.reduce((acc, n) => {
(acc[n.name] ??= ({ ...n, count: 0 })).count++;
return acc;
}, {}));
function uniqueWithCount(data, key, countKey) {
const getKey = key instanceof Function ? key : n => n[key];
const unique = new Map;
for (const n of data) {
const k = getKey(n);
unique.set(k, unique.get(k) ?? { ...n, [countKey]: 0 }).get(k)[countKey]++;
}
return unique;
}
const result = [...uniqueWithCount(arr, 'name', 'count').values()];
const table = document.querySelector('тут селектор вашей таблицы');
table.querySelectorAll('tbody td:last-child').forEach(
(n, i, { [~-i]: { innerText: prev } = {} }) =>
n.innerText !== prev && (n.innerHTML = `<a href="#">${n.innerText}</a>`)
);
// или
let prev = null;
for (const { rows } of table.tBodies) {
for (const { lastElementChild: n } of rows) {
const curr = n.textContent;
if (curr !== prev) {
n.innerHTML = '<a href="#">' + (prev = curr) + '</a>';
}
}
}
// создаём новый массив
const newArr = arr.map(({ name, ...n }) => (n.user_name = name, n));
// изменяем существующий:
arr.forEach(n => (n.user_name = n.name, delete n.name));
// keys - объект вида { старый_ключ_1: 'новый_ключ_1', старый_ключ_2: 'новый_ключ_2', ... }
const renameKeys = (obj, keys) =>
Object.fromEntries(Object
.entries(obj)
.map(([ k, v ]) => [ keys.hasOwnProperty(k) ? keys[k] : k, v ])
);
const newArr = arr.map(n => renameKeys(n, { name: 'user_name' }));
function renameKeys(obj, keys) {
for (const n of Object.entries(keys)) {
if (obj.hasOwnProperty(n[0])) {
obj[n[1]] = obj[n[0]];
delete obj[n[0]];
}
}
}
arr.forEach(n => renameKeys(n, { name: 'user_name' }));
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
.