const keys = [ 'city', 'country' ];
.const newArr = arr.map(n => Object.fromEntries(Object.values(n).map((v, i) => [ keys[i], v ])));
arr.forEach(n => Object.entries(n).forEach(([ k, v ], i) => (delete n[k], n[keys[i]] = v)));
str.replace(/\t.*/s, '')
// или
str.match(/^[^\t]*/)[0]
// или
str.slice(0, str.search(/\t|$/))
// или
str.split('\t', 1).pop()
// или
[...str].reduceRight((acc, n) => n === '\t' ? '' : n + acc, '')
const $menuItems = $('#menu a');
$('#submenu > ul').width(i => $menuItems.eq(i).width());
const min = 7;
const max = min + 21;
function update(value) {
value = Math.max(min, Math.min(max, value | 0));
$('#spinner2').val(value);
$('#slider2').slider('value', value);
const date = new Date();
date.setDate(date.getDate() + value);
$('#amount').val(date.toLocaleString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
}));
}
$('#slider2').slider({
range: 'min',
min,
max,
step: 1,
slide: (e, ui) => update(ui.value),
});
$('#spinner2').spinner({
min,
max,
spin: (e, ui) => update(ui.value),
}).on('input', e => update(e.target.value)).trigger('input');
const sort = {
number: (a, b) => a - b,
string: (a, b) => a.localeCompare(b),
};
function sortTable(table, colIndex) {
if (typeof table === 'string') {
table = document.querySelector(table);
}
const head = table.tHead.rows[0];
const compare = sort[head.cells[colIndex].dataset.type] ?? sort.string;
const value = row => row.cells[colIndex].innerText;
const tbody = table.tBodies[0];
tbody.append(...[...tbody.rows].sort((a, b) => compare(value(a), value(b))));
[...head.cells].forEach((n, i) => n.classList.toggle('sorted', i == colIndex));
}
.sorted {
background: #ccc;
}
.sorted::after {
content: " \2193";
}
// просто дёргаем сортировку
sortTable('#grid', 0);
sortTable(document.querySelector('table'), 1);
// или, сортируем по клику на заголовки столбцов
document.querySelectorAll('#grid th').forEach(function(n) {
n.addEventListener('click', this);
}, ({ target: t }) => sortTable(t.closest('table'), t.cellIndex));
<div class="phone">8 (123) 111-22-33</div>
<div class="phone">8 (456) 444-55-66</div>
<div class="phone">8 (789) 777-88-99</div>
document.querySelectorAll('.phone').forEach(n => {
const phone = n.innerHTML;
n.innerHTML = phone.slice(0, -4) + '... - <span>показать</span>';
n.querySelector('span').addEventListener('click', () => n.innerHTML = phone);
});
function filter(val) {
if (!(val instanceof Object)) {
return val;
}
const filtered = Object
.entries(val)
.map(n => [ n[0], filter(n[1]) ])
.filter(n => n[1]);
return filtered.length
? val instanceof Array
? filtered.map(n => n[1])
: Object.fromEntries(filtered)
: null;
}
const elements = document.querySelectorAll('.price');
const output = document.querySelector('.min-sum');
output.textContent = Math.min(...Array.from(
elements,
n => parseFloat(n.textContent)
));
// или
output.innerText = Array.prototype.reduce.call(
elements,
(min, n) => (
n = +n.innerText.match(/[\d.]+/),
n < min ? n : min
),
Infinity
);
const elem = document.querySelector('#elem').nextElementSibling;
if (elem) {
const num = 1 + [...elem.parentNode.children].indexOf(elem);
elem.innerText = num + '. ' + elem.innerText;
}
const elem = document.querySelector('#elem + *');
if (elem) {
let num = 1;
for (let n = elem; n = n.previousElementSibling; num++) ;
elem.textContent = `${num}. ${elem.textContent}`;
}
const elems = document.querySelector('ul').children;
const index = -~Array.prototype.findIndex.call(elems, n => n.id === 'elem');
if (index) {
elems[index]?.insertAdjacentText('afterbegin', ''.concat(-~index, '. '));
}
Как наиболее короче сделать...
generalDiv.innerHTML = newCats
.filter(n => n?.breeds.length)
.map(({ url, breeds: [ b ] }) => `
<div class="cat__item">
<div class="cat__img"><img src="${url}" alt="${b.name}"></div>
<div class="cat__name">${b.name}</div>
<div class="cat__temperament">${b.temperament}</div>
<div class="cat__live">${b.life_span}</div>
<div class="cat__origin">${b.origin}</div>
<div class="cat__description">${b.description}</div>
<div class="cat__wikipedia_url">${b.wikipedia_url}</div>
</div>
`)
.join('');
document.querySelector('form').addEventListener('input', function() {
const sum = Array.prototype.reduce.call(
this.querySelectorAll('input:checked'),
(acc, n) => acc + +n.value,
0
);
document.querySelector('#pSumma').innerText = `$${sum.toFixed(2)}`;
});
document.querySelectorAll('.g-project__words-moving').forEach(n => {
const html = n.querySelector('.words-moving__calm span').outerHTML.repeat(10);
n.querySelectorAll('.running-string-wrapp').forEach(m => m.innerHTML = html);
});
.words-moving__calm span
, вместо того, чтобы ограничиться только теми, которые лежат внутри текущего элемента .g-project__words-moving
. Для исправления можно перенести объявление place
в начало тела внешнего цикла, заменив при этом document
на boxes[i]
. const SHOW_MORE = 3;
const itemSelector = '.item';
const hiddenClass = 'd-none';
const hiddenSelector = `.${hiddenClass}`;
const $show = $('.show');
const $hide = $('.hide');
const $items = $(itemSelector);
function updateButtons() {
$show.toggleClass(hiddenClass, $items.filter(hiddenSelector).length === 0);
$hide.toggleClass(hiddenClass, $items.not(hiddenSelector).length === SHOW_MORE);
}
$show.click(function() {
$items.filter(hiddenSelector).slice(0, SHOW_MORE).removeClass(hiddenClass);
updateButtons();
}).click();
$hide.click(function() {
$items.slice(SHOW_MORE).addClass(hiddenClass);
updateButtons();
});
Object
.entries({ defaultTest, systemTest })
.flatMap(([ k, { references, ...n } ]) => references.map(m => ({
...m,
...n,
[k]: true,
})))
Object
.entries({ defaultTest, systemTest })
.map(([ k, v ]) => v.map(({ references, ...n }) => references.map(m => ({
...m,
...n,
[k]: true,
}))))
.flat(2)
const setOptions = (el, options, placeholder) =>
el.innerHTML =
`<option hidden selected value="">${placeholder}</option>` +
options.map(n => `<option>${n}</option>`).join('');