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));
чекбокс.addEventListener('change', e => кнопка.disabled = !e.target.checked);
$('.elem_block').on('click', '.dell', function() {
$(this).closest('.block').addClass('fx_none');
$('.no-res').toggleClass('fx_none', !!$('.block:not(.fx_none)').length);
});
document.addEventListener('click', e => {
const btn = e.target.closest('.dell');
if (btn) {
btn.closest('.block').classList.add('fx_none');
document.querySelector('.no-res').classList.toggle(
'fx_none',
!!document.querySelector('.block:not(.fx_none)')
);
}
});
fx_none
вырезаем.no-res
и .elem_block
добавляем общую обёртку, какой-нибудь <div class="container">
.dell
вместо добавления класса, скрывающего элементы, удаляем их по-настоящему:document.querySelectorAll('.dell').forEach(function(n) {
n.addEventListener('click', this);
}, e => e.target.closest('.block').remove());
.no-res
, если в .elem_block
что-то есть:.container:has(.elem_block *) .no-res {
display: none;
}
.no-res
надо в том случае, если существует .block
без класса, которые его скрывает:.container:has(.block:not(.fx_none)) .no-res {
display: none;
}
const controls = document.querySelectorAll('.segmented-control');
controls.forEach(n => n.addEventListener('change', updatePillPosition));
window.addEventListener('resize', () => controls.forEach(n => updatePillPosition.call(n)));
function updatePillPosition() {
const inputs = [...this.querySelectorAll('.option input')];
const x = this.offsetWidth / inputs.length * inputs.findIndex(n => n.checked);
this.querySelector('.selection').style.transform = `translateX(${x}px)`;
}
const SHOW_ON_LOAD = 3;
const SHOW_MORE = 2;
const items = [...document.querySelectorAll('.box-list__item')];
const button = document.querySelector('.show-more');
showItems(SHOW_ON_LOAD);
button.addEventListener('click', () => showItems(SHOW_MORE));
function showItems(count) {
items.splice(0, count).forEach(n => n.classList.add('ui-box-active'));
button.classList.toggle('ui-button-hidden', !items.length);
}