app.directive(directives);
const numbers = (str.match(/>\d+/g) ?? []).map(n => +n.slice(1));
// или
const numbers = Array.from(str.matchAll(/(?<=>)\d+/g), Number);
// или
const numbers = (function get(reg) {
const m = reg.exec(str)?.[1];
return m ? [ parseInt(m), ...get(reg) ] : [];
})(/>(\d+)/g);
''.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);
почему-то в данные изменение попадает только после nextTick'а (т.е. когда что-то побуждает родительский компонент перерисоваться)
$ids = array_unique(array_column($arr, 'user_id'));
$result = array_filter($arr2, fn($n) => !in_array($n['users_id'], $ids));
айдишник удаляемой строки это сугубо системная информация, никак не влияющая на отображение
const [ delId, setDelId ] = useState(null);<button onClick={() => setDelId(row.id)}>Delete<Modal isVisible={!!delId}><button onClick={() => setDelId(null)}>CloseThe useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.
найти объект
найти самое большое значение
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 => Object.is(m.value, n.value)))
// или
arr.filter((n, i, a) => i === a.findIndex(m => 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)