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 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 arr = zip([ arr1, arr2 ]);
. 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 : [].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 {
results[index] = await tasks[index]();
} 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
), {})
function haveSameValues(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
const count = new Map;
arr1.forEach(n => count.set(n, -~count.get(n)));
arr2.forEach(n => count.set(n, ~-count.get(n)));
for (const n of count.values()) if (n) {
return false;
}
return true;
}
haveSameValues(
[ 'hello, world!!', 0, 0, 0, 1, 1, false, false ],
[ false, false, 1, 1, 0, 0, 0, 'hello, world!!' ]
) // true
haveSameValues(
[ 1, 2, 3 ],
[ 3, 2, 2 ]
) // false
haveSameValues(
[],
[]
) // true
const arr = Array.from(
new Set(Array.from(document.querySelectorAll('.shop_name'), n => n.innerText)),
n => ({ name: n })
);
const arr = Object.values(Array.prototype.reduce.call(
document.getElementsByClassName('shop_name'),
(acc, { textContent: name }) => (acc[name] ??= { name }, acc),
{}
));
wrapper.innerHTML = Array
.from(word.value, n => obj[n] ? `<img src="${obj[n]}">` : '')
.join('');
for (let n = null; n = wrapper.lastChild; n.remove()) ;
for (const n of word.value) {
if (obj.hasOwnProperty(n)) {
const img = new Image;
img.src = obj[n];
wrapper.append(img);
}
}
// или
wrapper.replaceChildren(...Array.prototype.reduce.call(
word.value,
(acc, n) => (
obj[n] && ((acc[acc.length] = new Image).src = obj[n]),
acc
),
[]
));
while (word.value.length < wrapper.children.length) {
wrapper.removeChild(wrapper.lastElementChild);
}
while (word.value.length > wrapper.children.length) {
wrapper.appendChild(document.createElement('img'));
}
Array.prototype.forEach.call(wrapper.children, (n, i) => {
const src = obj[word.value[i]];
if (!(n.hidden = !src)) {
n.src = src;
}
});
let obj = { 'а': 'https://github.com/itsFide/converter/blob/master/img/а.png?raw=true', 'А': 'https://github.com/itsFide/converter/blob/master/img/а.png?raw=true', 'б':'https://github.com/itsFide/converter/blob/master/img/б.png?raw=true', ...
const obj = Object.fromEntries(Array.prototype.flatMap.call(
'абвгдеёжзийклмнопрстуфхцчшщъыьэюя', n => {
const url = `https://github.com/itsFide/converter/blob/master/img/${n}.png?raw=true`;
return [
[ n, url ],
[ n.toUpperCase(), url ],
];
}
));
function getPaths(obj, path = [ '' ]) {
const entries = Object.entries(obj);
return entries.length
? entries.reduce((acc, n) => (
path.push(n[0]),
acc.push(...getPaths(n[1], path)),
path.pop(),
acc
), [])
: [ path.join('/') ];
}