<script defer src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.3.4/cdn.min.js"></script>
<div x-data="{
items: [
{ id: 69, text: 'hello, world!!' },
{ id: 187, text: 'fuck the world' },
{ id: 666, text: 'fuck everything' },
],
}">
<template x-for="(n, i) in items">
<div>
<span x-text="n.text"></span>
<button @click="items.splice(i, 1)">x</button>
</div>
</template>
</div>
Код, который работает некорректно...
Object.freeze
назначить новое свойство уже не получится. Можно записать итератор в прототип массива (ну и после того, как он отработает, вернуть оригинальный итератор на место):const originalIterator = Array.prototype[Symbol.iterator];
Array.prototype[Symbol.iterator] = function() {
let i = -1;
return {
next: () => (i += 2) < arr.length
? { done: false, value: this[i] }
: { done: true },
};
};
setTimeout(() => Array.prototype[Symbol.iterator] = originalIterator, 0);
const result = arr.flat();
// или
const result = Array.prototype.concat.apply([], arr);
// или
const result = arr.reduce((acc, n) => (acc.push(...n), acc), []);
// или
const result = [];
for (const n of arr) {
for (const m of n) {
result[result.length] = m;
}
}
document.querySelectorAll('.filter__item').forEach(n => {
n.style.display = Array
.from(n.querySelectorAll('.filter__checkgroup-count'))
.some(m => +m.innerText.trim())
? 'block'
: 'none';
});
.hidden {
display: none;
}
for (const n of document.getElementsByClassName('filter__item')) {
n.classList.toggle('hidden', Array.prototype.every.call(
n.getElementsByClassName('filter__checkgroup-count'),
m => Number(m.textContent.trim()) === 0
));
}
function isEqual(a, b) {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(n => a[n] === b[n]);
}
const result = arr1.concat(arr2.filter(n => arr1.every(m => !isEqual(n, m))));
const unique = function(arr, keys = n => n) {
const picked = new Map;
return arr.filter((...args) => {
const p = []
.concat(keys(...args))
.reduce((acc, k) => acc.set(k, acc.get(k) ?? new Map).get(k), picked);
return !p.set(this, p.has(this)).get(this);
});
}.bind(Symbol());
const result = unique([ ...arr1, ...arr2 ], n => [ n.teamId, n.userId ]);
const zip = (...arrs) =>
arrs[0]?.map((n, i) => arrs.map(m => m[i])) ?? [];
const result = zip(arr1, arr2);
const zip = (arrs, defaultValue = null) =>
Array.from(
{ length: Math.max(...arrs.map(n => n.length)) },
(n, i) => arrs.map(m => i < m.length ? m[i] : defaultValue)
);
// или
const zip = (arrs, defaultValue = null) =>
arrs.reduce((acc, n, i) => (
n.forEach((m, j) => (acc[j] ??= Array(arrs.length).fill(defaultValue))[i] = m),
acc
), []);
const result = zip([ arr1, arr2 ]);
.zip([ [ 1, 2, 3 ], [], [ 99 ] ], Infinity)
- в результате получим[
[ 1, Infinity, 99 ],
[ 2, Infinity, Infinity ],
[ 3, Infinity, Infinity ]
]
function* zip(data, defaultValue = null) {
const iterators = Array.from(data, n => n[Symbol.iterator]());
for (let doneAll = false; (doneAll = !doneAll);) {
const values = [];
for (const n of iterators) {
const { value, done } = n.next();
values.push(done ? defaultValue : value);
doneAll &&= done;
}
if (!doneAll) {
yield values;
}
}
}
const result = [...zip([ arr1, arr2 ])];
.Array.from(zip((function*() {
yield [ , true, false, NaN ];
yield 'abcde';
yield Array(3).keys();
})()))
[
[ undefined, 'a', 0 ],
[ true, 'b', 1 ],
[ false, 'c', 2 ],
[ NaN, 'd', null ],
[ null, 'e', null ]
]
const chunked = (arr, chunkSize) =>
arr.reduce((acc, n, i) => (
(i % chunkSize) || acc.push([]),
acc.at(-1).push(n),
acc
), []);
console.log(chunked([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], 3));
const group = (data, key) =>
Array.prototype.reduce.call(
data,
(acc, n, i, a) => ((acc[key(n, i, a)] ??= []).push(n), acc),
{}
);
const chunked = (data, chunkSize) =>
Object.values(group(data, (_, i) => i / chunkSize | 0));
console.log(chunked('0123456789', 3));
console.log(chunked(document.querySelectorAll('img'), 5));
const chunked = (data, chunkSize, slice = data.slice) =>
Array.from(
{ length: Math.ceil(data.length / chunkSize) },
function(_, i) {
return this(i * chunkSize, (i + 1) * chunkSize);
},
(slice instanceof Function ? slice : Array.prototype.slice).bind(data)
);
console.log(chunked('abcdefghij', 4)); // так кусками будут тоже строки
console.log(chunked('abcdefghij', 4, [].slice)); // а так - массивы
console.log(chunked($('img'), 5));
function* chunked(data, chunkSize) {
let chunk = [];
for (const n of data) {
if (chunk.push(n) === chunkSize) {
yield chunk;
chunk = [];
}
}
if (chunk.length) {
yield chunk;
}
}
console.log(Array.from(chunked([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], 3)));
console.log([...chunked(document.querySelectorAll('img'), 5)]);
for (const n of chunked(Array(10).keys(), 4)) {
console.log(n);
}
const index = arr1.findIndex(n => arr2.indexOf(n) !== -1);
// просто массив индексов
const indices = arr1.reduce((acc, n, i) => (arr2.includes(n) && acc.push(i), acc), []);
// объект вида { элемент: индекс первого вхождения }
const indices = arr2.reduce((acc, n) => (
acc[0].hasOwnProperty(n) && (acc[1][n] = acc[0][n]),
acc
), [ arr1.reduce((acc, n, i) => (acc[n] ??= i, acc), {}), {} ])[1];
// Map вида { элемент: массив всех индексов данного элемента }
const indices = arr1.reduce((acc, n, i) => (
acc[0].has(n) && acc[1].set(n, acc[1].get(n) ?? []).get(n).push(i),
acc
), [ new Set(arr2), new Map ])[1];
const runTasks = (tasks, max = 1) =>
new Promise(resolve => {
const results = Array(tasks.length).fill(null);
let started = 0;
let finished = 0;
for (let i = Math.max(1, Math.min(max, tasks.length)); i--; run()) ;
async function run() {
if (finished === tasks.length) {
resolve(results);
} else if (started < tasks.length) {
const index = started++;
try {
const result = tasks[index]();
results[index] = result instanceof Promise ? await result : result;
} catch (e) {
results[index] = e;
}
finished++;
run();
}
}
});
const sendRequests = (urls, ...args) =>
runTasks(urls.map(n => () => fetch(n).then(r => r.json())), ...args);
const printf = (str, ...params) =>
str.replace(/\$(\d+)/g, (m, g1) => params[~-g1] ?? m);
const groupedAndSortedArr = Object
.values(arr.reduce((acc, n) => ((acc[n[0]] ??= []).push(n), acc), {}))
.sort((a, b) => a[0][0].localeCompare(b[0][0]));
str.split('=').pop()
// или
str.slice(str.indexOf('=') + 1)
str.replace(/[^=]*=/, '')
// или
str.match(/(?<==).*/)[0]
// или
/[^=]*$/.exec(str).shift()
new URLSearchParams(str).get('sort')
Array
.from(new URLSearchParams(str))
.reduce((acc, [ k, v ]) => (
k.endsWith('[]')
? (acc[k.slice(0, -2)] ??= []).push(v)
: acc[k] = v,
acc
), {})
const result = arr.filter(n => arr2.includes(n.strategy));
const result = arr2.flatMap(function(n) {
return this[n] ?? [];
}, arr.reduce((acc, n) => ((acc[n.strategy] ??= []).push(n), acc), {}));
const result = arr.filter(((values, n) => values.has(n.strategy)).bind(null, new Set(arr2)));
const result = [];
for (const n of arr) {
for (const m of arr2) {
if (m === n.strategy) {
result.push(n);
break;
}
}
}