arr.map(id => people.find(n => n.id === id))
// или
arr.map(function(n) {
return this[n];
}, people.reduce((acc, n) => (acc[n.id] = n, acc), {}))
people.filter(n => arr.includes(n.id))
// или
people.filter(((ids, n) => ids.has(n.id)).bind(null, new Set(arr)))
<ul>
<li><span>aaa</span></li>
<li>
<span>bbb</span>
<ul>
<li><span>bbb.1</span></li>
<li>
<span>bbb.2</span>
<ul>
<li><span>bbb.2.1</span></li>
<li><span>bbb.2.2</span></li>
</ul>
</li>
<li>
<span>bbb.3</span>
<ul>
<li>
<span>bbb.3.1</span>
<ul>
<li><span>bbb.3.1.1</span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
document.querySelectorAll('li').forEach(n => {
const count = ((n.querySelector('ul') || {}).children || []).length;
n.querySelector('span').textContent += ` (${count})`;
});
document.querySelectorAll('li').forEach(n => {
const count = n.querySelectorAll('li').length;
n.querySelector('span').textContent += ` (${count})`;
});
undefined
относится к falsy значениям, так что с помощью оператора ||
подставляйте пустой объект (или какое-нибудь другое значение - смотрите сами, как вам удобнее) там, где нужное значение может отсутствовать, например:(((lead._embedded.items[0].custom_fields.find(cf => cf.id == PRODUCT_FIELD_ID) || {}).values || {})[0] || {}).value || null
lead._embedded.items[0].custom_fields.find(cf => cf.id == PRODUCT_FIELD_ID)?.values[0].value ?? null
const className = 'класс элементов';
.document.querySelectorAll(`.${className}`).forEach((n, i) => {
n.innerText = arr[i];
});
// или
for (const [ i, n ] of document.querySelectorAll(`.${className}`).entries()) {
n.innerHTML = arr[i];
}
// или
arr.forEach(function(n, i) {
this.item(i).textContent = n;
}, document.getElementsByClassName(className));
// или
const elems = document.getElementsByClassName(className);
for (let i = 0; i < elems.length; i++) {
elems[i].appendChild(document.createTextNode(arr[i]));
}
$(window).scroll(function onScroll() {
if ($(this).scrollTop() > 777) {
$('.div_clone').clone().appendTo('.container2');
$(this).off('scroll', onScroll);
}
});
const isAllUnique = (...args) => new Set(args).size === args.length;
console.log(isAllUnique(69, 187, 666)); // true
console.log(isAllUnique(2, 2, 3, 4)); // false
console.log(isAllUnique(...'ABCDA')) // false
const elems = [...document.querySelectorAll('.class1')];
const index = elems.findIndex(n => n.classList.contains('class2'));
const elems = document.querySelectorAll('.class1');
let index = elems.length;
while (--index >= 0 && !elems[index].matches('.class2')) ;
const index = Array.prototype.indexOf.call(
document.querySelectorAll('.class1'),
document.querySelector('.class2')
);
<div class="country">
<input class="country-code">
<img class="country-flag">
</div>
function updateFlag(el) {
const country = countries.find(n => !el.value.indexOf(n.code));
el.closest('.country').querySelector('.country-flag').src = country ? country.flag : '';
}
document.addEventListener('input', function(e) {
if (e.target.classList.contains('country-code')) {
updateFlag(e.target);
}
});
document.querySelectorAll('.country-code').forEach(updateFlag);
const countries = [
{ code: ..., flag: ... },
{ code: ..., flag: ... },
...
];
const country = countries.find(n => !inputCode.value.indexOf(n.code));
inputFlag.src = country ? country.flag : '';
<input type="number" min="0" max="100">
<table>
<tbody></tbody>
</table>
const input = document.querySelector('input');
const table = document.querySelector('table');
input.addEventListener('input', ({ target: t }) => {
const count = t.value = Math.max(0, t.value | 0);
const [ tbody ] = table.tBodies;
const { rows } = tbody;
for (; rows.length > count; tbody.deleteRow(-1)) ;
while (rows.length < count) {
const row = tbody.insertRow();
row.insertCell().textContent = '#' + rows.length;
row.insertCell().textContent = Math.random() * 1e3 | 0;
}
});
// или
input.oninput = function() {
const count = this.value = Math.max(0, +this.value || 0);
const tbody = table.querySelector('tbody');
const rows = tbody.children;
Array.prototype.slice.call(rows, Math.min(rows.length, count)).forEach(n => n.remove());
tbody.insertAdjacentHTML('beforeend', Array
.from({ length: Math.max(0, count - rows.length) }, (n, i) => `
<tr>
<td>#${rows.length + i + 1}</td>
<td>${Math.floor(Math.random() * 1000)}</td>
</tr>`)
.join('')
);
};
document.addEventListener('click', function(e) {
if (!e.target.closest('.tileset-showitems')) {
tilesetShowListRemove();
}
});
- .active {
+ .active .box {
const containerSelector = '.tileset-showitems';
const buttonSelector = `${containerSelector} .tileset-showitems-trigger`;
const activeClass = 'active';
const closeAllExcept = container => document
.querySelectorAll(`${containerSelector}.${activeClass}`)
.forEach(n => n !== container && n.classList.remove(activeClass));
document.addEventListener('click', ({ target: t }) => {
const button = t.closest(buttonSelector);
const container = t.closest(containerSelector);
if (button) {
container.classList.toggle(activeClass);
}
closeAllExcept(container);
});
window.addEventListener('keydown', e => e.key === 'Escape' && closeAllExcept());
for (const n of el.options) {
for (const m of elValue) {
if (n.value === m) {
n.selected = true;
break;
}
}
}
Array.prototype.forEach.call(
el,
n => n.selected = elValue.includes(n.value)
);
el
.querySelectorAll(elValue.map(n => `[value="${n}"]`))
.forEach(n => n.selected = true);
а где в верстке у тебя эти точки указаны?
const points = [
{ max: 200, text: 'hello, world!!' },
{ max: 800, text: 'fuck the world' },
{ max: Infinity, text: 'fuck everything' },
];
window.addEventListener('scroll', function() {
const
scroll = document.documentElement.scrollTop,
{ text } = points.find(n => n.max >= scroll);
document.querySelector('.fixed').textContent = text;
});
const newArr = arr.map(function({ ...n }) {
return this.reduce((acc, k) => (acc[k] = acc[k].toLowerCase(), acc), n);
}, [ 'firstName', 'lastName' ]);
const keys = [ 'firstName', 'lastName' ];
arr.forEach(n => keys.forEach(k => n[k] = n[k].toLowerCase()));
const data = $('table tr')
.get()
.map(tr => $('input', tr).get().map(n => $(n).val()))
.filter(row => row[row.length - 1])
.map(row => `(${row.map(n => `'${n}'`).join(', ')})`);
const data = Array.prototype.reduce.call(
document.querySelector('table').rows,
(acc, { cells, lastElementChild: last }) => (
last.lastElementChild.value && acc.push(`(${Array
.from(cells, n => `'${n.lastElementChild.value}'`)
.join(', ')})`
),
acc
),
[]
);
Как поправить код?
const discounts = [
{ percent: 0, sum: 0 },
{ percent: 2, sum: 4000 },
{ percent: 3, sum: 10000 },
{ percent: 4, sum: 20000 },
{ percent: 5, sum: 50000 },
];
const discount = discounts.reduce((p, c) => c.sum <= pricechange ? c : p);
const discountedPrice = pricechange * (100 - discount.percent) / 100;
const discounts = [
{ percent: 0, sum: 4000 },
{ percent: 2, sum: 10000 },
{ percent: 3, sum: 20000 },
{ percent: 4, sum: 50000 },
{ percent: 5, sum: Infinity },
];
const discount = discounts.find(n => n.sum > pricechange);