const arrs = [ arr1, arr2 ];
), дальше есть варианты:const result = arrs[0].map((_, i) => arrs.flatMap(arr => arr[i]));
const result = arrs.reduce((acc, arr) => (
arr.forEach((n, i) => (acc[i] ??= []).push(...n)),
acc
), []);
const result = [];
for (const arr of arrs) {
for (const [ i, n ] of arr.entries()) {
if (!result[i]) {
result[i] = [];
}
for (const m of n) {
result[i][result[i].length] = m;
}
}
}
watch: {
'product.qty'(val) {
this.product.qty = Math.max(1, Math.min(99, val | 0));
},
},
v-for
и это элемент массива, то можно установить глубокое наблюдение за всем массивом:watch: {
products: {
deep: true,
handler: val => val.forEach(n => n.qty = Math.max(1, Math.min(99, n.qty | 0))),
},
},
methods: {
onInput(e) {
if (e.isTrusted) {
e.target.value = Math.max(1, Math.min(99, e.target.value | 0));
e.target.dispatchEvent(new Event('input'));
}
},
},
<input
@input="onInput"
...
function onInput({ isTrusted, target: t }) {
if (isTrusted) {
t.value = Math.max(t.min, Math.min(t.max, t.value | 0));
t.dispatchEvent(new Event('input'));
}
}
const minmaxDirective = {
mounted: el => el.addEventListener('input', onInput),
unbind: el => el.removeEventListener('input', onInput),
};
app.directive('minmax', minmaxDirective);
<input
v-minmax
min="1"
max="99"
...
document.querySelectorAll('.item').forEach((n, i) => n.dataset.priority = ++i);
// или
for (const [ i, n ] of document.querySelectorAll('.item').entries()) {
n.setAttribute('data-priority', i + 1);
}
// или
const items = document.getElementsByClassName('item');
for (let i = 0; i < items.length; i++) {
items[i].attributes['data-priority'].value = -~i;
}
e.get('target').properties.get('имяСвойстваСодержащегоId')
shop.id
)?<div data-id="{{ properties.имяСвойстваСодержащегоId }}">
где ошибка?
const maxlen = Math.max(...arr.map(n => n.length));
// или
const maxlen = arr.reduce((max, { length: n }) => max > n ? max : n, -Infinity);
fetch('https://gorest.co.in/public/v1/posts')
.then(r => r.json())
.then(r => {
// собираем разметку
document.body.insertAdjacentHTML('beforeend', `
<ul>${r.data.map(n => `
<li>
<a>${n.title}</a>
</li>`).join('')}
</ul>
`);
// или, создаём элементы напрямую
const ul = document.createElement('ul');
ul.append(...r.data.map(n => {
const li = document.createElement('li');
const a = document.createElement('a');
a.textContent = n.title;
li.append(a);
return li;
}));
document.body.append(ul);
});
const type = x => x == null ? x : x.constructor;
type() === undefined // true
type(null) === null // true
type(/./) === RegExp // true
type(187) === Number // true
type(type) === Function // true
const typename = x => x?.constructor.name ?? `${x}`;
typename() // 'undefined'
typename(null) // 'null'
typename(false) // 'Boolean'
typename('hello, world!!') // 'String'
typename({}) // 'Object'
typename([]) // 'Array'
typename(document.body) // 'HTMLBodyElement'
typename(document.getElementsByClassName('xxx')) // 'HTMLCollection'
typename(new class XXX {}) // 'XXX'
typename((c => new class YYY extends c {})(class XXX {})) // 'YYY'
typename(typename) // 'Function'
.xxx {
background: red;
}
.xxx:hover {
background: orange;
}
.xxx .v-chip__content {
color: white;
font-weight: bold;
}
<v-chip-group active-class="xxx">
this.circle = new ymaps.Circle(
...
watch: {
радиусКруга(val) {
this.circle.geometry.setRadius(val);
},
...
const circle = new ymaps.Circle(
...
);
this.$watch('радиусКруга', val => circle.geometry.setRadius(val));
const AccordionItem = ({ title, opened, toggle, children }) => (
<div>
<button onClick={toggle}>{title}</button>
{opened && children}
</div>
);
const Accordion = ({ items }) => {
const [ opened, setOpened ] = useState(null);
return (
<div>
{items.map((n, i) => (
<AccordionItem
title={n.title}
opened={i === opened}
toggle={setOpened.bind(null, i === opened ? null : i)}
>
<p>{n.text}</p>
</AccordionItem>
))}
</div>
);
};
false
, повторно (т.е., представлен в более чем одном из исходных массивов) будет true
; хватаем элементы, которые false
:const diff = (...arrs) => Array
.from(arrs
.flatMap(arr => [...new Set(arr)])
.reduce((acc, n) => acc.set(n, acc.has(n)), new Map))
.reduce((acc, n) => (n[1] || acc.push(n[0]), acc), []);
Map
, где ключами будут элементы вложенных массивов, а значениями множества вложенных массивов, где присутствует данный элемент. Получаем те ключи, где размер множества равен единице:const diff = (...arrs) => Array
.from(arrs.reduce((acc, arr) => (
arr.forEach(n => acc.set(n, acc.get(n) ?? new Set).get(n).add(arr)),
acc
), new Map))
.reduce((acc, n) => (n[1].size === 1 && acc.push(n[0]), acc), []);
Map
и Set
- проверяем, что элемент вложенного массива отсутствует во всех других вложенных массивах и в результирующем массиве:const diff = (...arrs) =>
arrs.reduce((acc, arr) => (
arr.forEach(n =>
arrs.every(m => m === arr || !m.includes(n)) &&
!acc.includes(n) &&
acc.push(n)
),
acc
), []);
data: () => ({
items: [
{ checked: false, label: '...' },
{ checked: false, label: '...' },
...
],
}),
<label v-for="n in items">
<input type="checkbox" v-model="n.checked">
{{ n.label }}
</label>
computed: {
get() {
return this.items.every(n => n.checked);
},
set(val) {
this.items.forEach(n => n.checked = val);
},
},
<label>
<input type="checkbox" v-model="all">
ALL
</label>
document.querySelector('.calc_container').addEventListener('input', e => {
const block = e.target.closest('.calc_block');
const price = +block.querySelector('.price span').innerText;
const count = +e.target.value;
block.querySelector('.summ span').innerText = price * count;
const orderData = Array
.from(e.currentTarget.querySelectorAll('.calc_block'), n => ({
name: n.querySelector('label').innerText,
count: +n.querySelector('.count').value,
sum: +n.querySelector('.summ span').innerText,
}))
.filter(n => n.count);
document.querySelector('.total_block span').innerText = orderData
.reduce((acc, n) => acc + n.sum, 0);
document.querySelector('textarea').value = orderData
.map(n => `Название: ${n.name} | Количество: ${n.count}`)
.join('\n');
});
const chunkedAndTransposed = ([ headers, ...arr ], chunkSize) =>
arr.reduce((acc, n, i) => (
(i % chunkSize) || acc.push(headers.map(m => [ m ])),
n.forEach((m, j) => acc.at(-1)[j].push(m)),
acc
), []);
const result = chunkedAndTransposed(arr, 2);
const chunkedAndTransposed = (arr, chunkSize, defautlValue = null) =>
Array.from({ length: Math.ceil((arr.length - 1) / chunkSize) }, (_, iChunk) =>
Array.from({ length: arr[0].length }, (_, iCol) =>
Array.from({ length: chunkSize + 1 }, (_, iRow) =>
iRow ? arr[iChunk * chunkSize + iRow]?.[iCol] ?? defautlValue : arr[0][iCol]
)
)
);
const result = chunkedAndTransposed(arr, 5);