const propsCount = 3;.const newObj = Object.fromEntries(Object
.entries(obj)
.sort((a, b) => a[1] - b[1])
.slice(-propsCount)
);Object
.entries(obj)
.sort((a, b) => b[1] - a[1])
.slice(propsCount)
.forEach(n => delete obj[n[0]]);
str.match(/(?<=>)\d+/g) ?? []
// или
str.match(/>\d+/g)?.map(n => n.slice(1)) ?? []
// или
Array.from(str.matchAll(/>(\d+)/g), n => n[1])
''.concat(...Array.from(str, n => n.repeat(2)))
// или
str.replace(/./g, '$&$&')
// или
str.replace(/./g, m => Array(3).join(m))
// или
str.replace(/(?=.)/g, (m, i) => str[i])
// или
[...str].flatMap(n => Array(2).fill(n)).join('')
// или
[].map.call(str, n => `${n}${n}`).join``
// или
str.split('').reduce((acc, n) => acc + n + n, '')
const averageAge = arr.reduce((acc, n) => acc + n.age, 0) / arr.length;function avg(data, key = n => n) {
const getVal = key instanceof Function ? key : n => n[key];
let sum = 0;
let count = 0;
for (const n of data) {
sum += getVal(n);
count += 1;
}
return sum / count;
}const averageAge = avg(arr, 'age');.avg(Array(10).keys()) // 4.5
avg('12345', Number) // 3
avg(document.images, n => n.width) // сами посмотрите, сколько тут получится
arr.reduce((acc, n, i) => (
(!i || n === 1) && acc.push([]),
acc[acc.length - 1].push(n),
acc
), [])
const index = arr.reduce((min, n, i, a) => a[min]?.length <= n.length ? min : i, -1);
if (index !== -1) {
arr[index] = arr[index][0].toUpperCase() + arr[index].slice(1);
}const [ indexes ] = arr.reduce((min, n, i) => (
n.length < min[1] && (min = [ [], n.length ]),
n.length === min[1] && min[0].push(i),
min
), [ [], Infinity ]);
indexes.forEach(n => arr[n] = arr[n].replace(/./, m => m.toUpperCase()));
const date = new Date(str.replace(/\S+/, m => m.split('.').reverse().join('-')));const date = new Date(str.replace(/(\d+)\.(\d+)\.(\d+)/, '$3-$2-$1'));const [ day, month, year, hours, minutes, seconds ] = str.split(/\D/);
const date = new Date(year, month - 1, day, hours, minutes, seconds);const date = dayjs(str, 'DD.MM.YYYY HH:mm:ss').toDate();
function sort([...arr]) {
const max = arr.reduce((max, n) => max?.population > n.population ? max : n, null);
return arr.sort((a, b) => a === max ? -1 : b === max ? 1 : a.city.localeCompare(b.city));
}
const className = 'model';const elements = document.querySelectorAll(`.${className}`);
// или
const elements = document.getElementsByClassName(className);const getText = el => el.textContent;
// или
const getText = el => el.innerText;
// или
const getText = el => el.innerHTML;
// или
const getText = el => el.lastChild.nodeValue;
// или
const getText = el => el.childNodes[0].data;const result = Array.from(elements, getText).join(', ');
// или
const result = ''.concat(...[...elements].flatMap((n, i) => (
n = getText(n),
i ? [ ', ', n ] : n
)));
// или
const result = Array.prototype.reduce.call(
elements,
(acc, n, i) => acc + (i ? ', ' : '') + getText(n),
''
);
// или
const result = (function get(i, n = elements[i]) {
return n
? `${i ? ', ' : ''}${getText(n)}${get(i + 1)}`
: ''
})(0);
const { x: countX = 0, o: countO = 0 } = Array
.from(str.toLowerCase())
.reduce((acc, n) => (acc[n] = (acc[n] ?? 0) + 1, acc), {});const [ countX, countO ] = [ /x/i, /o/i ].map(n => ~-str.split(n).length);
найти объект
найти самое большое значение
const obj = arr.flat().reduce((max, n) => max?.age > n.age ? max : n, null);const val = Math.max(...arr.flat().map(n => n.age));const objs = arr.reduce((acc, n) => (
n.forEach(m => (
m.age > acc[0] && (acc = [ m.age, [] ]),
m.age === acc[0] && acc[1].push(m)
)),
acc
), [ -Infinity, [] ])[1];
[...new Map(arr.map(n => [ n.value, n ])).values()]
// или
Object.values(arr.reduce((acc, n) => (acc[n.value] ??= n, acc), {}))arr.filter(function(n) {
return !(this[n.value] = this.hasOwnProperty(n.value));
}.bind({}))
// или
arr.filter(function({ value }) {
return !this.set(value, this.has(value)).get(value);
}, new Map)
// или
arr.filter(((picked, { value: n }) => !picked.has(n) && picked.add(n)).bind(null, new Set))arr.filter((n, i, a) => n === a.find(m => m.value === n.value))
// или
arr.filter((n, i, a) => i === a.findIndex(m => Object.is(m.value, n.value)))Array.from(
new Set(arr.map(n => n.value)),
n => arr.find(m => m.value === n)
)
// или
arr
.slice()
.sort((a, b) => a.value.localeCompare(b.value))
.filter((n, i, a) => n.value !== a[i - 1]?.value)
const newArr = Array
.from(arr.reduce((acc, n) => acc.set(n, (acc.get(n) ?? 0) + 1), new Map))
.filter(n => n[1] === 1)
.map(n => n[0]);arr.splice(0, arr.length, ...Array
.from(arr.reduce((acc, n) => acc.set(n, acc.has(n)), new Map))
.reduce((acc, n) => (n[1] || acc.push(n[0]), acc), [])
);
Знаю, что можно сделать с помощью split и прочими способами,...
str.slice(0, -3).replace(',', '')str.split(':', 2).join(':').split(',').join('')...но нужно элегантное решение
str.replace(/,|.{3}$/g, '')str.replace(/(\d+.\d+.\d+)..(\d+.\d+).*/, '$1 $2')
Math.max(0, ...arr.reduce((acc, n, i, a) => (
n !== a[i - 1] && acc.push(0),
acc[acc.length - 1]++,
acc
), []))arr.reduce((acc, n, i, a) => (
n !== a[~-i] && (acc[1] = 0),
acc[0] = acc[+(++acc[1] > acc[0])],
acc
), [ 0, 0 ])[0]
for (let i = 1; i < arr.length; i++) {
if (arr[i] === arr[i - 1]) {
for (let j = i--; ++j < arr.length; arr[j - 1] = arr[j]) ;
arr.pop();
}
}arr.reduceRight((_, n, i, a) => i && n === a[i - 1] && a.splice(i, 1), null);arr.splice(0, arr.length, ...arr.filter((n, i, a) => !i || a[i - 1] !== n));arr.length -= arr.reduce((acc, n, i, a) => (
a[i - acc] = n,
acc + (i && n === a[i - 1 - acc])
), 0);
function sort(arr, order, key = n => n) {
const positions = new Map(order.map((n, i) => [ n, i ]));
const getPosition = n => positions.get(key(n)) ?? Number.MAX_SAFE_INTEGER;
return arr.sort((a, b) => getPosition(a) - getPosition(b));
}function sorted(arr, order, key = n => n) {
const ordered = new Map(order.map(n => [ n, [] ]));
const unordered = [];
arr.forEach(n => (ordered.get(key(n)) ?? unordered).push(n));
return [].concat(...ordered.values(), unordered);
}a1 = [ '999', '290', '999', '222', '333', '987', '309', '666', '999' ];
a2 = [ '999', '222', '666' ];
sorted(a1, a2) // [ '999', '999', '999', '222', '666', '290', '333', '987', '309' ]
a1 = [ 12, 34, 6, 2, 55, 523, 23, 333, 16, 51 ];
a2 = [ 3, 5, 2 ];
sorted(a1, a2, n => +`${n}`[0]) // [ 34, 333, 55, 523, 51, 2, 23, 12, 6, 16 ]
a1 = [ 666, 'xxx', () => [], true, 1, () => null, false, 'aaa', [0] ];
a2 = [ 'boolean', 'string', 'function' ];
sort(a1, a2, n => typeof n);
a1 // [ true, false, 'xxx', 'aaa', () => [], () => null, 666, 1, [ 0 ] ]
.active {
background: red;
}document.querySelector('table').addEventListener('change', ({ target: t }) => {
t.closest('tr').classList.toggle('active', t.checked);
});
// или
document.querySelectorAll('table tr').forEach(function(n) {
n.addEventListener('change', this);
}, e => e.currentTarget.classList.toggle('active', e.target.checked));tr:has(.form-check-input:checked) {
background: red;
}
const names = Array.from(
document.querySelectorAll('#mainTable input:checked'),
n => n.name
);const names = Array.prototype.reduce.call(
document.getElementById('mainTable').getElementsByTagName('input'),
(acc, n) => (n.checked && acc.push(n.getAttribute('name')), acc),
[]
);