computed: {
ids() {
return this.strings.map(n => this.objects.find(m => m.title === n)?.id);
},
// или
ids() {
const ids = this.objects.reduce((acc, n) => (acc[n.title] = n.id, acc), {});
return this.strings.map(n => ids[n] ?? 'Получить id не удалось - объекта с указанным title нет');
},
// или
idByTitle() {
return Object.fromEntries(this.objects.map(n => [ n.title, n.id ]));
},
ids() {
const ids = this.idByTitle;
return this.strings.reduce((acc, n) => (
Object.hasOwn(ids, n) && acc.push(ids[n]),
acc
), []);
},
// или
stringsSet() {
return new Set(this.strings);
},
ids() {
return this.objects.reduce((acc, n) => (
this.stringsSet.has(n.title) && acc.push(n.id),
acc
), []);
},
// или
idsByTitle() {
return this.objects.reduce((acc, n) => (
(acc[n.title] ??= []).push(n.id),
acc
), []);
},
ids() {
return this.strings.flatMap(n => this.idsByTitle[n] ?? []);
},
},computed, к сожалению не подходит
value из первого массива аналогичное значение code во втором)? Если это не важно и вас устраивает возможное получение undefined, тогдаconst result = array1.map(n => array2.find(m => m.code === n.value));const obj2 = Object.fromEntries(array2.map(n => [ n.code, n ]));
const result = array1.reduce((acc, n) => (
(n = obj2[n.value]) && acc.push(n),
acc
), []);const result = array1.map(function({ value: n }) {
return this.get(n) ?? `объект с code="${n}" отсутствует`;
}, new Map(array2.map(n => [ n.code, n ])));code во втором массиве быть неуникальны? Если да, и надо получать все объекты с указанными code, а не один, то можно предварительно сгруппировать второй массив по значениям code:const result = array1.flatMap(function(n) {
return this[n.value] ?? [];
}, array2.reduce((acc, n) => ((acc[n.code] ??= []).push(n), acc), {}));array2, то его и надо перебирать при извлечении объектов, а не первый массив:const result = array2.filter(function(n) {
return this.has(n.code);
}, new Set(array1.map(n => n.value)));
e.target.dataset.followerStylee.target? Ну, когда вы наводите курсор на слайд с data-атрибутом. На тот слайд, который не видно за вложенной в него картинкой.target хватать, а пытаться найти у него предка с нужным вам атрибутом.
const result = Object.values(arr.reduce((max, n) => (
max[n.group] = +max[n.group]?.score > +n.score ? max[n.group] : n,
max
), {}));function group(data, key, val = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const getVal = val instanceof Function ? val : n => n[val];
const result = new Map;
for (const n of data) {
const k = getKey(n);
result.set(k, result.get(k) ?? []).get(k).push(getVal(n));
}
return result;
}
function max(data, key = n => n) {
const getVal = key instanceof Function ? key : n => n[key];
let result = null;
for (const n of data) {
const val = getVal(n);
result = result?.[1] >= val ? result : [ n, val ];
}
return result?.[0];
}const result = Array.from(
group(arr, 'group').values(),
n => max(n, m => +m.score)
);
// значения withSeat вместо раскладывания в отдельные переменные собираете в объект
const withSeat = {
adult: 1,
teenager: 1,
babe: 0,
};
const passengers = cabins.flatMap(n => Object
.entries(n)
.flatMap(([ k, v ]) => Array.from(
{ length: v },
() => ({ withSeat: withSeat[k] })
))
);
const obj = Object.fromEntries(Object
.entries(arr
.flatMap(Object.entries)
.reduce((acc, n) => ((acc[n[0]] ??= new Set).add(n[1]), acc), {}))
.map(([ k, v ]) => [ k, v.size === 1 ? [...v][0] : null ])
);const obj = arr.reduce((acc, n) => (
Object.keys(n).forEach(k => {
acc[k] = Object.hasOwn(acc, k) && n[k] !== acc[k] ? null : n[k];
}),
acc
), {});
v-model.lazy.
def order_weight(string):
return { n: sum(map(int, n)) for n in string.split() }
const current = ref(props.value);emits("change", current);@change="changeCount"function changeCount(value) { count.value = value; }
emits("change", current); ---> emits("change", current.value);
formatDate(date) {
const today = new Date();
return [ 'getFullYear', 'getMonth', 'getDate' ].every(n => date[n]() === today[n]())
? 'Today'
: flatpickr.formatDate(date, 'j M');
},
const groupSelector = 'fieldset.js-tree-box';
const mainSelector = 'legend input';
const itemSelector = 'legend + span input';
const activeClass = 'active';
document.addEventListener('change', ({ target: t }) => {
const group = t.closest(groupSelector);
if (group) {
const main = group.querySelector(mainSelector);
const items = [...group.querySelectorAll(itemSelector)];
if (main === t) {
items.forEach(n => n.checked = t.checked);
} else {
const numChecked = items.reduce((acc, n) => acc + n.checked, 0);
main.checked = numChecked === items.length;
main.indeterminate = 0 < numChecked && numChecked < items.length;
}
group.classList.toggle(activeClass, main.checked);
}
});
const sorted = (data, key) => Array
.from(data, n => [ n, key(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);document.querySelector('.result').append(...sorted(
document.querySelector('.data').cloneNode(true).children,
n => +n.innerText
));
делегирование не работает
в консоли выдает "e.target.closest is not a function"
const hoverCellNum = hoverCell.getAttribute('data-tdnum');
document.addEventListener('mouseenter', ({ target: t }) => {
if (t.matches?.('td._hight-light__cell')) {
t.closest('tbody').querySelectorAll('.table-big__row').forEach(n => {
n.cells[t.cellIndex].classList.add('_hover');
});
}
}, true);
document.addEventListener('mouseleave', e => {
if (e.target.matches?.('td._hight-light__cell')) {
document.querySelectorAll('._hover').forEach(n => n.classList.remove('_hover'));
}
}, true);
document.addEventListener('click', updateCounter);
document.addEventListener('input', updateCounter);
document.querySelectorAll('.tariff__counter').forEach(n => {
const max = n.dataset.seats;
n.querySelectorAll('.tariff__counter-max').forEach(m => m.innerText = max);
n.querySelectorAll('.amount').forEach(m => m.max = max);
n.querySelectorAll('button').forEach(m => m.dataset.change = m.innerText === '+' ? 1 : -1);
});
function updateCounter({ target: t }) {
const input = t.closest('.tariff__counter-block')?.querySelector('.amount');
if (input) {
const { min, max, value } = input;
input.value = Math.max(min, Math.min(max, (value | 0) + (t.dataset.change | 0)));
}
}
const [posts, setPosts] = useState([]);setPosts(fetchReq);const fetchReq = fetch(`${fetchURL}/posts`).then(res => res.json());
fetch(`${fetchURL}/posts`)
.then(r => r.json())
.then(setPosts);
const amounts = [ 5, 10, 15 ];
const [ amount, setAmount ] = useState(null);
const [ isCustomAmount, setIsCustomAmount ] = useState(false);{amounts.map(n => (
<label>
<input
type="radio"
disabled={isCustomAmount}
checked={amount === n && !isCustomAmount}
onChange={() => setAmount(n)}
/>
${n}
</label>
))}
<label>
<input
type="checkbox"
checked={isCustomAmount}
onChange={e => (setAmount(null), setIsCustomAmount(e.target.checked))}
/>
Другая сумма
</label>
{isCustomAmount && <input value={amount} onChange={e => setAmount(+e.target.value)} />}
<input type="hidden" name="amountusd" value={amount} />
const keys = [ 'id', 'secondId' ];
const result = firstArray.map(n => secondArray.find(m => keys.every(k => n[k] === m[k])) ?? n);const arrToTree = (arr, keys) =>
arr.reduce((acc, n) => (
keys.reduce((p, c, i) => p[n[c]] ??= i + 1 === keys.length ? n : {}, acc),
acc
), {});
const keys = [ 'id', 'secondId' ];
const tree = arrToTree(secondArray, keys);
const result = firstArray.map(n => keys.reduce((p, c) => p?.[n[c]], tree) ?? n);const arrToTree = (arr, keys) =>
arr.reduce((acc, n) => (
keys(n).reduce(
(p, c, i, a) => p.set(c, p.get(c) ?? (-~i === a.length ? n : new Map)).get(c),
acc
),
acc
), new Map);
const keys = n => [ n.id, n.secondId ];
const result = firstArray.map(function(n) {
return keys(n).reduce((p, c) => p?.get(c), this) ?? n;
}, arrToTree(secondArray, keys));