const merge = (key, ...arrs) =>
Object.values(arrs.flat().reduce((acc, n) => (
Object.assign(acc[n[key]] ??= {}, n),
acc
), {}));
const result = merge('id', sum, arr1, arr2);
const merge = (key, ...arrs) =>
Array.from(arrs.reduce((acc, arr) => arr.reduce((acc, n) => {
const k = key(n);
return acc.set(k, Object.assign(acc.get(k) ?? {}, n));
}, acc), new Map).values());
const result = merge(n => n.id, sum, arr1, arr2);
должен быть более лаконичный способ, чем плодить такие переменные
Или это считается нормальной практикой?
const result = arr.map(function(n) {
return this[n];
}, Object.fromEntries(sum.map(n => [ n.id, n.name ])));
// или
const names = new Map(sum.map(n => [ n.id, n.name ]));
const result = arr.map(n => names.get(n));
// или
const result = arr.map(n => sum.find(m => m.id === n)?.name);
sum
отсутствуют некоторые из нужных элементов, а получать undefined
внутри массива с результатами не хочется?const result = arr.map(function(n) {
return this[n] ?? 'объекта с таким id нет';
}, Object.fromEntries(sum.map(n => [ n.id, n.name ])));
const names = new Map(sum.map(n => [ n.id, n.name ]));
const result = arr.reduce((acc, n) => (names.has(n) && acc.push(names.get(n)), acc), []);
app.ifScroll =
ifScroll.value =
. document.querySelectorAll('.parent').forEach((n, i) => {
n.insertAdjacentHTML('beforeend', `<div class="child">${arr[i]}</div>`);
});
for (const [ i, n ] of document.querySelectorAll('.parent').entries()) {
n.append(document.createElement('div'));
n.lastChild.className = 'child';
n.lastChild.innerText = arr[i];
}
arr.forEach(function(n, i) {
const div = document.createElement('div');
div.classList.add('child');
div.textContent = n;
this[i].appendChild(div);
}, document.getElementsByClassName('parent'));
$('.parent').append(i => `<div class="child">${arr[i]}</div>`);
const [ checked, setChecked ] = React.useState(false);
<input
type="checkbox"
checked={checked}
onChange={e => setChecked(e.target.checked)}
...
<button
disabled={!checked}
...
нет примера их использования
<q-select
ref="select"
...
<q-btn
@click="$refs.select.showPopup()"
...
const createArr = length =>
Array.from({ length }, (_, i) =>
Array.from({ length }, (_, j) =>
(i === j || i === length - j - 1) +
((i <= j && i <= length - j - 1) || (i >= j && i >= length - j - 1))
)
);
const newArr = arr.reduce((acc, n) => (
acc.push({ ...n, fractionTotal: n.fraction + (acc.at(-1)?.fractionTotal ?? 0) }),
acc
), []);
// или
const newArr = arr.map(function({ ...n }) {
n.fractionTotal = this[0] += n.fraction;
return n;
}, [ 0 ]);
arr.forEach((n, i, a) => n.fractionTotal = n.fraction + (i && a[i - 1].fractionTotal));
// или
arr.reduce((acc, n) => n.fractionTotal = acc + n.fraction, 0);
const rows = 8;
const cols = 8;
document.body.innerHTML = Array
.from({ length: rows }, (_, i) => Array
.from({ length: cols }, (_, j) => (i ^ j) & 1)
.join(''))
.join('<br>');
const sorted = (data, keys) => Array
.from(data, n => [ n ].concat(keys(n)))
.sort((a, b) => {
let diff = 0;
for (let i = 0; ++i < a.length && !(diff = ((a[i] < b[i]) ? -1 : +(a[i] > b[i])));) ;
return diff;
})
.map(n => n[0]);
const sortChildren = (el, keys) =>
el.append(...sorted(el.children, keys));
const ul = document.querySelector('ul');
ul.addEventListener('change', e => sortChildren(
e.currentTarget,
el => [
-el.querySelector('input').checked,
el.innerText.trim().toLowerCase(),
]
));
ul.dispatchEvent(new Event('change'));
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
length = len(matrix)
for i in range(0, length // 2):
for j in range(i, length - i - 1):
matrix[i][j], \
matrix[j][length - i - 1], \
matrix[length - i - 1][length - j - 1], \
matrix[length - j - 1][i] \
= \
matrix[length - j - 1][i], \
matrix[i][j], \
matrix[j][length - i - 1], \
matrix[length - i - 1][length - j - 1]
arr.filter(RegExp.prototype.test.bind(/^[рим]+$/i))
// или
arr.filter(n => !n.match(/[^рим]/i))
// или
arr.filter(n => !n.replace(/р|и|м/gi, ''))
// или
arr.filter(n => [...n.toLowerCase()].every(m => 'рим'.includes(m)))
const uniqueWithSum = (arr, idKey, sumKey) =>
Object.values(arr.reduce((acc, n) => {
const id = n[idKey];
acc[id] ??= Object.assign(new n.constructor, n, { [sumKey]: 0 });
acc[id][sumKey] += n[sumKey];
return acc;
}, {}));
const result = uniqueWithSum(data, 'brand', 'price');
ul
в transition
следует завернуть li
в transition-group
:<transition-group tag="ul" name="fade" class="buttons">
<li
v-if="какое здесь будет условие, предлагаю подумать самостоятельно"
...
const itemSelector = '.radio';
const activeClass = 'active';
// конечно, вы можете и дальше продолжать ковырять jquery
const $items = $(itemSelector).on('change', function() {
$items.next().removeClass(activeClass);
$(this).next().addClass(activeClass);
});
// но ведь есть и другой путь
const items = document.querySelectorAll(itemSelector);
const onChange = ({ currentTarget: t }) =>
items.forEach(n => n.nextElementSibling.classList.toggle(activeClass, n === t));
items.forEach(n => n.addEventListener('change', onChange));
.radio:has(:checked) + .order__form-input {
/* сюда переносим стили, делающие input видимым */
}