const tables = document.querySelectorAll('селектор таблиц');for (const { tHead, tBodies } of tables) {
const labels = Array.prototype.map.call(
tHead.rows[0].cells,
th => th.textContent
);
for (const { rows } of tBodies) {
for (const { cells } of rows) {
for (const [ i, label ] of labels.entries()) {
cells[i].dataset.label = label;
}
}
}
}tables.forEach(table => {
table.querySelectorAll('tbody td').forEach(function(td) {
td.setAttribute('data-label', this[td.cellIndex]);
}, Array.from(table.querySelectorAll('thead th'), th => th.innerText));
});
const getPrimitives = data =>
data instanceof Object
? Object.values(data).flatMap(getPrimitives)
: [ data ];
const result = getPrimitives(obj).map(value => ({ value }));function* getPrimitives(data) {
if (data instanceof Object) {
for (const k in data) if (Object.hasOwn(data, k)) {
yield* getPrimitives(data[k]);
}
} else {
yield data;
}
}
const result = Array.from(getPrimitives(obj), n => ({ value: n }));function getNestedData(data, test, getter = n => n) {
const result = [];
for (const stack = [ data ]; stack.length;) {
const n = stack.pop();
if (n instanceof Object) {
stack.push(...Object.values(n).reverse());
}
if (test(n)) {
result.push(getter(n));
}
}
return result;
}
const resutl = getNestedData(obj, n => n !== Object(n), n => ({ value: n }));
const unique = function*(data, keys = n => n) {
const picked = new Map;
for (const n of data) {
const p = []
.concat(keys(n))
.reduce((acc, k) => acc.set(k, acc.get(k) ?? new Map).get(k), picked);
if (!p.set(this, p.has(this)).get(this)) {
yield n;
}
}
}.bind(Symbol());// собираем новый массив
const newArr = Array.from(unique(arr, n => [ n.name, n.value ]));
// обновляем существующий
arr.splice(0, arr.length, ...unique(arr, Object.values));
const result = data
.flatMap(n => n.values)
.filter(n => n.Ids.some(m => arr.includes(m)))
.map(({ id, title }) => ({ id, title }));const inArr = Set.prototype.has.bind(new Set(arr));
const data.reduce((acc, { values }) => (
values.forEach(({ Ids, ...n }) => Ids.some(inArr) && acc.push(n)),
acc
), []);
const result = allCass.filter(function(n) {
return !this.has(n.id);
}, new Set(defaultCass.map(n => n.id)));function* diff(data1, data2, key = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const keys = new Set;
for (const n of data2) {
keys.add(getKey(n));
}
for (const n of data1) {
if (!keys.has(getKey(n))) {
yield n;
}
}
}const result = [...diff(allCass, defaultCass, 'id')];Array.from(diff('abcdE', 'AcD', n => n.toLowerCase())) // ['b', 'E']for (const n of diff(Array(8).keys(), Array(5).keys())) {
console.log(n); // 5 6 7
}
Пытался сделать через reduce из библиотеки lodash
const newArr = _.map(_.groupBy(arr, 'merch'), (v, k) => ({
merch: +k,
games: _.uniq(_.flatMap(v, 'games')),
}));const newArr = Object
.entries(arr.reduce((acc, n) => ((acc[n.merch] ??= []).push(...n.games), acc), {}))
.map(n => ({ merch: +n[0], games: [...new Set(n[1])] }));
arr.sort((a, b) => a.surname.localeCompare(b.surname) || a.name.localeCompare(b.name));const sorted = (arr, keys) => arr
.map(n => [ n ].concat(keys(n)))
.sort((a, b) => {
let diff = 0;
a.find((n, i) => diff = i && ((n < b[i]) ? -1 : +(n > b[i])));
return diff;
})
.map(n => n[0]);
const sortedArr = sorted(arr, n => [ n.surname.toLowerCase(), n.name.toLowerCase() ]);
selects[0].appendChild(option) selects[1].appendChild(option)
Если данный дочерний элемент является ссылкой на существующий узел в документе, то функция appendChild() перемещает его из текущей позиции в новую позициюselects[1].appendChild(option.cloneNode(true));selects.forEach(function(n) {
n.append(...this.map(m => new Option(m[1].label, m[0])));
}, Object.entries(metrics.convertRules));const optionsHTML = Object
.entries(metrics.convertRules)
.map(n => `<option value="${n[0]}">${n[1].label}</option>`)
.join('');
selects.forEach(n => n.innerHTML = optionsHTML);
<form>, то доступна коллекция ссылок) и элемент, в который надо записать результат вычислений.document.addEventListener('input', e => {
if (e.target.classList.contains('form-control')) {
const form = e.target.closest('тут селектор формы');
form.querySelector('span').innerText = Array.prototype.reduce.call(
form.querySelectorAll('input.form-control'),
(acc, n) => acc * (+n.value || 0),
1
);
}
});
// или
document.addEventListener('input', ({ target: t }) => {
if (t.matches('.form-control')) {
t.form.querySelector('span').textContent = Array
.from(t.form.elements)
.reduce((acc, n) => acc * (n.value | 0), 1);
}
});
arr.reduce((acc, n) => (
n = n.match(/(\S+) = (.*)/),
n && (acc[n[1]] = n[2]),
acc
), {})Object.fromEntries(arr
.map(n => n.split(': ').pop().split(' = '))
.filter(n => n.length === 2)
)
const plusSelector = '.count-plus';
const minusSelector = '.count-minus';
function updateCount(el, change) {
const counterEl = el.closest('.count-wrapper').querySelector('.counter');
counterEl.innerText = Math.max(0, +counterEl.innerText + change);
}function setClickHandler(selector, change) {
document.querySelectorAll(selector).forEach(function(n) {
n.addEventListener('click', this);
}, e => updateCount(e.target, change));
}
setClickHandler(plusSelector, 1);
setClickHandler(minusSelector, -1);document.addEventListener('click', ({ target: t }) => {
const change = +t.matches(plusSelector) || -t.matches(minusSelector);
if (change) {
updateCount(t, change);
}
});
function sum(data, key = n => n) {
const getVal = key instanceof Function ? key : n => n[key];
let result = 0;
for (const n of data) {
result += +getVal(n) || 0;
}
return result;
}const $form = $('form').on('change', 'select', () => {
$('#result').val(sum($form.find('select'), n => $(n).val()));
});const input = document.querySelector('#result');
const selects = document.querySelectorAll('form select');
const onChange = () => input.value = sum(selects, 'value');
selects.forEach(n => n.addEventListener('change', onChange));document.querySelector('form').addEventListener('change', function(e) {
if (e.target.tagName === 'SELECT') {
document.getElementById('result').value = sum(
this.getElementsByTagName('select'),
n => n.selectedOptions[0].getAttribute('value')
);
}
});document.forms[0].onchange = ({ target: t }) => {
if (t.matches('select')) {
t.form.result.value = sum(
t.form.querySelectorAll('option:checked:not(:disabled)'),
n => n.attributes.value.value
);
}
};
let checked = null;
$('input').click(function() {
checked = checked === this.value ? null : this.value;
this.checked = !!checked;
});
// или
document.querySelectorAll('input').forEach(function(n) {
n.addEventListener('click', this);
}, function({ target: t }) {
t.checked = !!(this[0] = this[0] === t ? null : t);
}.bind([]));const $checkboxes = $('input').change(function() {
if (this.checked) {
$checkboxes.not(this).prop('checked', false);
}
});
// или
const checkboxes = document.querySelectorAll('input');
const onChange = e => checkboxes.forEach(n => n.checked &&= n === e.target);
checkboxes.forEach(n => n.addEventListener('change', onChange));
const sum5 = (...args) =>
args.length > 4
? args.slice(0, 5).reduce((acc, n) => acc + n, 0)
: sum5.bind(null, ...args);
// или
// : (...args2) => sum5(...args, ...args2);
const selects = [...document.querySelectorAll('select')];
const onChange = () =>
selects.forEach(function({ value, options: [...n] }) {
n.forEach(m => m.hidden = this(m.value) && value !== m.value);
}, Set.prototype.has.bind(new Set(selects.map(n => n.value))));
selects.forEach(n => n.addEventListener('change', onChange));
function transposeTable(table) {
const headerCol = table.rows[0]?.cells[1]?.tagName === 'TH';
const content = Array.from(
table.rows,
tr => Array.from(tr.cells, td => td.innerHTML)
);
table.innerHTML = content[0]?.map((n, i) => `
<tr>${content.map((m, j) => (j = (headerCol ? j : i) ? 'td' : 'th', `
<${j}>${m[i]}</${j}>`)).join('')}
</tr>
`).join('') ?? '';
}function transposeTable(table) {
const cells = Array.prototype.reduce.call(table.rows, (acc, tr) => (
Array.prototype.forEach.call(tr.cells, (n, i) => (acc[i] ??= []).push(n)),
acc
), []);
table.replaceChildren();
cells.forEach(n => table.insertRow().append(...n));
}
const weights = {
j: 11,
q: 12,
k: 13,
a: 14,
};
const isStraight = hand => hand
.map(n => weights[n] ?? +n)
.sort((a, b) => a - b)
.every((n, i, a) => !i || (n - a[i - 1] === 1));