function getUsersInfo(ids, callback) {
const results = [...Array(ids.length)];
ids.forEach((n, i) => {
getUserInfo(n, user => {
results[i] = user;
if (results.every(Boolean)) {
callback(result);
}
});
});
}
<div class="title" data-name="first">
<div class="title" data-name="second">
...
<div class="list" data-name="first">
<div class="list" data-name="second">
...
$('.title').click(function() {
$(`.list[data-name="${this.dataset.name}"]`).slideToggle('fast');
});
$('.title').click(function() {
$('.list').eq($(this).index()).slideToggle('fast');
});
.title
/.list
, тогда можно так:$('.title').click(function() {
$(this).closest('здесь селектор общего предка').find('.list').slideToggle('fast');
});
document.addEventListener('input', function(e) {
const inputsWrapper = e.target.closest('.класс-блоков-которые-содержат-ваши-инпуты');
if (inputsWrapper) {
const inputs = [...inputsWrapper.querySelectorAll('input')];
const lastInput = inputs.pop();
lastInput.value = inputs.map(n => n.value).join(' ');
}
});
str.slice(0, 3) + '-'.repeat(Math.max(0, str.length - 3))
// или
str.replace(/(?<=.{3})./g, '-')
// или
Array.from(str, (n, i) => i < 3 ? n : '-').join('')
// или
str.replace(/./g, (m, i) => i < 3 ? m : '-')
// или
str.match(/.{0,3}/) + Array(Math.max(0, str.length - 2)).join('-')
// или
str.substring(0, 3).padEnd(str.length, '-')
$('button').click(e => $('.title').text($(e.target).text()));
const onClick = e => document.querySelector('.title').innerText = e.target.innerText;
document.querySelectorAll('button').forEach(n => n.addEventListener('click', onClick));
document.addEventListener('click', ({ target: t }) => {
if (t.tagName === 'BUTTON') {
document.querySelector('.title').textContent = t.textContent;
}
});
const itemSelector = '.product';
const activeClass = 'checked';
const disabledClass = 'unchecked';
const activeLimit = 3;
document.addEventListener('click', e => {
const cl = e.target.closest(itemSelector)?.classList;
if (cl && !cl.contains(disabledClass)) {
cl.toggle(activeClass);
updateDisabled();
}
});
updateDisabled();
function updateDisabled() {
const [ notActive, active ] = Array.prototype.reduce.call(
document.querySelectorAll(itemSelector),
(acc, n) => (acc[+n.classList.contains(activeClass)].push(n), acc),
[ [], [] ]
);
const limitReached = activeLimit <= active.length;
notActive.forEach(n => n.classList.toggle(disabledClass, limitReached));
}
const items = [...document.querySelectorAll(itemSelector)];
let activeCount = 0;
items.forEach(n => n.addEventListener('click', onClick));
updateDisabled(items.filter(n => n.classList.contains(activeClass)).length);
function onClick({ currentTarget: { classList: cl } }) {
if (!cl.contains(disabledClass)) {
updateDisabled(cl.toggle(activeClass) ? 1 : -1);
}
}
function updateDisabled(change) {
const limitReached = (activeCount += change) >= activeLimit;
for (const { classList: cl } of items) {
cl.toggle(disabledClass, !cl.contains(activeClass) && limitReached);
}
}
<button data-step="-1">-</button>
<input value="1">
<button data-step="+1">+</button>
const values = [ 1, 2, 4, 6, 8, 10, 12, 16, 20, 24, 32, 48, 56, 64 ];
for (const n of document.querySelectorAll('[data-step]')) {
n.addEventListener('click', onClick);
}
function onClick() {
const input = document.querySelector('input');
const index = +this.dataset.step + values.indexOf(+input.value);
input.value = values[Math.max(0, Math.min(values.length - 1, index))];
}
const totalPrice = Array
.from(el.closest('.calc').querySelectorAll('.range__control'))
.reduce((acc, n) => acc * n.value, 1);
$('select').change(function() { ... }).change();
Object.values(arr.reduce((acc, { id, value }) => {
const type = typeof value;
acc[id] = acc[id] ?? { id };
acc[id][type] = (acc[id][type] ?? 0) + 1;
return acc;
}, {}))
const createTree = (data, index = []) =>
data.reduce((ul, { children: c }, i) => {
index.push(i);
const li = document.createElement('li');
li.innerText = index.join('_');
if (Array.isArray(c) && c.length) {
li.appendChild(createTree(c, index));
}
ul.appendChild(li);
index.pop();
return ul;
}, document.createElement('ul'));
// или
const createTree = (data, index = []) =>
data instanceof Array && data.length
? `<ul>${data.map((n, i) => `
<li>
${(index.push(i), index.join('_'))}
${createTree(n.children, index)}
${(index.pop(), '')}
</li>`).join('')}
</ul>`
: '';
const filtered = arrWithObj.filter(n => !arr.includes(n.id));
// или
const filtered = arrWithObj.filter(function(n) {
return !this.has(n.id);
}, new Set(arr));
// или
const filtered = Array.from(arr.reduce(
(acc, n) => (acc.delete(n), acc),
new Map(arrWithObj.map(n => [ n.id, n ]))
).values());
const ul = document.querySelector('.ul-parent');
const groupedNodes = [...ul.children].reduce((acc, n) => {
const k = n.textContent[0].toLowerCase();
(acc[k] = acc[k] ?? []).push(n);
return acc;
}, {});
ul.replaceWith(...Object.entries(groupedNodes).map(n => {
const ul = document.createElement('ul');
ul.classList.add('ul-parent', n[0] + '-litter');
ul.append(...n[1]);
return ul;
}));
const ul = document.querySelector('.ul-parent');
const groupedHTML = Array.prototype.reduce.call(
ul.children,
(acc, { innerText: [ c ], outerHTML }) => {
const k = c.toLowerCase();
(acc[k] = acc[k] ?? []).push(outerHTML);
return acc;
},
{}
);
ul.outerHTML = Object
.entries(groupedHTML)
.map(([ k, v ]) => `<ul class="ul-parent ${k}-litter">${v.join('')}</ul>`)
.join('');
document.addEventListener('click', e => {
const div = e.target.closest('button')?.closest('div');
if (div) {
console.log(div.id);
}
});
document.querySelectorAll('div button').forEach(function(n) {
n.addEventListener('click', this);
}, e => console.log(e.currentTarget.closest('div').id));
arr.sort((a, b) => (a.rooms - b.rooms) || (a.square - b.square));
// или, в более общем виде
const sort = (arr, ...keys) =>
arr.sort((a, b) => {
let diff = 0;
keys.find(k => diff = a[k] - b[k]);
return diff;
});
sort(arr, 'rooms', 'square');
const sorted = (arr, keys) => arr
.map(n => [ n ].concat(keys(n)))
.sort((a, b) => {
let diff = 0;
for (let i = 0; ++i < a.length && !(diff = a[i] - b[i]);) ;
return diff;
})
.map(n => n[0]);
const sortedArr = sorted(arr, n => [ n.rooms, n.square ]);