undefined
, вместо которого с помощью nullish coalescing подставляем просто цену. А чтобы не копипастить извлечение цены, вынесем его в отдельную функцию, которую, как и сам сортируемый массив, можно сделать параметром функции сортировки.const sorted = (arr, key) => arr
.map(n => [ n, key(n) ])
.sort((a, b) => a[1] - b[1])
.map(n => n[0]);
const sortedArr = sorted(arr, n => -(n.price.new ?? n.price).replace(/\D/g, ''));
const uniqueObj = (obj, key = val => val) =>
Object.fromEntries(Object
.entries(obj)
.filter(function(n) {
const k = key(n[1], n[0]);
return !this.has(k) && this.add(k);
}, new Set)
);
const getMaxIndexes = (arr, count) => Object
.entries(arr.reduce((acc, n, i) => ((acc[n] = acc[n] ?? []).push(i), acc), {}))
.sort((a, b) => b[0] - a[0])
.flatMap(n => n[1])
.slice(0, count);
$slider.find('.ul-slider-handle').html(`<img src="${imageSrc}">`);
slide(e, ui) {
$(this).find('.ui-slider-handle img').css('opacity', в зависимости от ui.value);
},
<div data-color="black"></div>
<div data-color="white"></div>
document.addEventListener('click', ({ target: { dataset: { color } } }) => {
if (color) {
document.querySelector('button').dataset.id = color;
}
});
// или
const button = document.querySelector('button');
const onClick = e => button.setAttribute('data-id', e.target.getAttribute('data-color'));
document.querySelectorAll('[data-color]').forEach(n => n.addEventListener('click', onClick));
$('.btn-show').on('click', function() { $(this).toggleClass('.flip'); });
'flip'
, без точки..btn-show
- вот там и дёргайте toggleClass. const arr = Array.from({ length: max - min + 1 }, (n, i) => i + min);
function* range(start, stop, step) {
if (stop === undefined) {
stop = start;
start = 0;
}
if (start === stop) {
step = 1;
}
if (step === undefined) {
step = Math.sign(stop - start);
}
if (start <= stop && step > 0 || start >= stop && step < 0) {
for (let i = start; step < 0 ? i >= stop : i <= stop; i += step) {
yield i;
}
}
}
console.log(Array.from(range(3, 9))); // [3, 4, 5, 6, 7, 8, 9]
console.log([...range(-5)]); // [0, -1, -2, -3, -4, -5]
for (const n of range(100, 200, 33)) {
console.log(n); // 100 133 166 199
}
const r = range(12, -7, -5);
for (let n; !(n = r.next()).done; ) {
console.log(n.value); // 12 7 2 -3
}
const replacements = {
worksAmount: 187,
reviewsAmount: 666,
};
const newStr = str.replace(/\$\$\[(\w+)\]/g, (m, g1) => replacements[g1] ?? m);
async function chain(arr) {
const result = [];
for (const item of arr) {
result.push(await item(result[result.length - 1]));
}
return result;
}
function chain(arr) {
const result = [];
return arr
.reduce((prev, curr) => prev.then(curr).then(r => (result.push(r), r)), Promise.resolve())
.then(() => result);
}
const find = (arr, id) =>
(Array.isArray(arr) ? arr : []).reduce((found, n) =>
found ?? (n.id === id ? n : find(n.children, id))
, null);
const obj = find(arr, id);
if (obj) {
obj.isSelected = isSelected;
}
arr.reduce((acc, n) => acc + +(n.startsWith(`${currency} `) && n.match(/\d+$/)), 0)
arr.reduce((acc, n) => {
const [ currency, sum ] = n.split(' ');
acc[currency] = (acc[currency] ?? 0) + +sum;
return acc;
}, {})
const getTypeGroup = el => el.dataset.type.replace(/\d/g, '');
// или
const getTypeGroup = el => el.getAttribute('data-type').match(/\D+/)[0];
// или
const getTypeGroup = el => el.attributes['data-type'].value.split(/\d/).shift();
document.addEventListener('click', e => {
const el = e.target.closest('[data-type]');
if (el) {
console.log(getTypeGroup(el));
}
});
// или
document.querySelectorAll('[data-type]').forEach(function(n) {
n.addEventListener('click', this);
}, e => console.log(getTypeGroup(e.currentTarget)));
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)
);
const parentSelector = '.row-module';
const wrapperTag = 'div';
const wrapperClass = 'wrap';
const wrapSize = 4;
for (const $n of chunked($(parentSelector).children(), wrapSize)) {
$n.wrapAll(`<${wrapperTag} class="${wrapperClass}">`);
}
const parent = document.querySelector(parentSelector);
chunked(parent.children, wrapSize).forEach(n => {
parent.append(document.createElement(wrapperTag));
parent.lastChild.classList.add(wrapperClass);
parent.lastChild.append(...n);
});
const containerSelector = '.tabs';
const headerSelector = `${containerSelector} .tabs-nav__item`;
const contentSelector = `${containerSelector} .tab`;
const activeClass = 'is-active';
function setActiveTab(header) {
if (header instanceof Element && header.matches(headerSelector)) {
const container = header.closest(containerSelector);
const headers = container.querySelectorAll(headerSelector);
const contents = container.querySelectorAll(contentSelector);
const index = Array.prototype.indexOf.call(headers, header);
const toggle = (n, i) => n.classList.toggle(activeClass, i === index);
headers.forEach(toggle);
contents.forEach(toggle);
}
}
// делегирование, подключаем обработчик клика один раз для всех
document.addEventListener('click', e => {
setActiveTab(e.target.closest(headerSelector));
});
// или, назначаем обработчик клика индивидуально каждому заголовку
document.querySelectorAll(headerSelector).forEach(function(n) {
n.addEventListener('click', this);
}, e => setActiveTab(e.currentTarget));