if (sortArray[i]) {
0
? Тогда этот элемент обработан не будет - не попадёт в результирующий массив. О чём, кстати, и говорится в сообщении об ошибке, в возвращаемом вами отсортированном массиве элементов меньше, чем в исходном:expected [ Array(14980) ] to deeply equal [ Array(15000) ]
i
всегда существует, так что засовывать в firstArray
его следует без проверок.function pendulum(arr) {
arr.sort((a, b) => a - b);
const head = [];
const tail = [];
for (let i = 0; i < arr.length; i += 2) {
head.push(arr[i]);
if (i + 1 < arr.length) { // или if (arr.hasOwnProperty(i + 1)) {
tail.push(arr[i + 1]);
}
}
return [ ...head.reverse(), ...tail ];
}
const pendulum = arr => arr
.sort((a, b) => a - b)
.reduce((acc, n, i) => (acc[i & 1].push(n), acc), [ [], [] ])
.flatMap((n, i) => i ? n : n.reverse());
href="javascript:deleteRow(this);"
onclick="deleteRow(this)"
.document.querySelector('table').addEventListener('click', e => {
const btn = e.target.closest('.btn');
if (btn) {
btn.closest('tr').remove();
}
});
нашел другой вариант
$('body').on('click', 'btn btn-warning', function() { $(this).parents('tr').remove(); });
НО проблема в том, что при нажатии удаляется полностью все строки, которые...
$('body').on('click', '.btn.btn-warning', function(e) {
e.preventDefault();
$(this).closest('tr').remove();
});
#
ссылкам в href. sendRequesr
вместо строки с городом соответствующий ей элемент <a>
. {"value":"[\"2b2df5f4-256d-402e-b074-c460ee394a2e
[
видите? - value (days тоже) это строка, а не массив. Так что не хватает JSON.parse
. tbody
у таблицы? Одна штука:document.querySelector('tbody').addEventListener('input', function() {
const data = Array.from(
this.children,
tr => Array.from(tr.querySelectorAll('input'), input => input.value)
);
console.log(data);
});
document.querySelector('table').addEventListener('input', e => {
const { map, flatMap } = Array.prototype;
const data = flatMap.call(
e.currentTarget.tBodies,
tbody => map.call(
tbody.rows,
tr => map.call(tr.cells, td => td.lastElementChild.value)
)
);
console.log(data);
});
// или
document.querySelector('table').addEventListener('input', function() {
const numHeadRows = this.querySelectorAll('thead tr').length;
const data = [];
for (const input of this.querySelectorAll('tbody input')) {
const td = input.parentNode;
const iCol = td.cellIndex;
const iRow = td.parentNode.rowIndex - numHeadRows;
(data[iRow] ??= [])[iCol] = input.value;
}
console.log(data);
});
document.querySelectorAll('.top > .nick').forEach(function(n) {
const text = n.textContent;
!this.has(text) && this.add(text) || n.remove();
}, new Set);
[...document.querySelector('.top').children].reduce((acc, n) => {
const text = n.innerText;
acc.includes(text) ? n.parentNode.removeChild(n) : acc.push(text);
return acc;
}, []);
Object
.values(Array
.from(document.querySelectorAll('.top > .nick'))
.reduce((acc, n) => ((acc[n.innerText] ??= []).push(n), acc), {}))
.forEach(n => n.forEach((m, i) => i && (m.outerHTML = '')));
const el = document.querySelector('.top');
el.innerHTML = [...new Set(el.innerHTML.match(/<span.*?\/span>/g) ?? [])].join(' ');
const el = document.querySelector('.top');
el.innerHTML = Array
.from(el.getElementsByClassName('nick'), n => n.innerText)
.filter((n, i, a) => i === a.indexOf(n))
.reduce((acc, n) => acc + (acc && ' ') + `<span class="nick">${n}</span>`, '');
class DoublyLinkedList {
constructor() {
this.size = 0;
this.head = null;
this.tail = null;
}
add(value, index) {
index ??= this.size;
const next = this.searchByIndex(index);
const prev = next ? next.prev : this.tail;
const node = { value, next, prev };
prev || (this.head = node);
next || (this.tail = node);
prev && (prev.next = node);
next && (next.prev = node);
this.size++;
}
_remove(node) {
if (node) {
node.prev || (this.head = node.next);
node.next || (this.tail = node.prev);
node.prev && (node.prev.next = node.next);
node.next && (node.next.prev = node.prev);
this.size--;
}
}
removeByValue(value) {
this._remove(this.searchByValue(value));
}
removeByIndex(index) {
this._remove(this.searchByIndex(index, true));
}
searchByIndex(index, strict) {
if (!(index >= 0 && index <= this.size - !!strict)) {
throw 'invalid index';
}
let node = this.head;
while (index--) {
node = node.next;
}
return node;
}
searchByValue(value, startIndex = 0) {
let node = this.searchByIndex(startIndex, true);
while (node && node.value !== value) {
node = node.next;
}
return node;
}
}
function max(data, key = n => n) {
const getVal = key instanceof Function ? key : n => n[key];
return Array.prototype.reduce.call(data, (max, n) => {
const val = getVal(n);
return max[0] > val ? max : [ val, n ];
}, [ -Infinity, undefined ])[1];
}
const { text } = max(arr, n => n.text.length);
const oldest = max(arr, 'age');
const remove = {
from: 5,
exclude: [ 9, 10, 11 ],
};
$('table tr').each(function() {
$(this)
.children()
.filter(i => i >= remove.from && !remove.exclude.includes(i))
.remove();
});
function getWeekdaysOfMonth(year, month) {
const date = new Date(year, --month, 1);
const result = [];
while (date.getMonth() === month) {
result.push(date.toLocaleString('ru-RU', {
month: 'long',
day: 'numeric',
weekday: 'long',
}));
date.setDate(date.getDate() + 1);
}
return result;
}
const weekdaysOfDecember2020 = getWeekdaysOfMonth(2020, 12);
но как поступить если я не хочу забирать дни недели из стандартного объекта. а взять из их своего массива?
const weekdays = [
'воскресенье',
'это понедельник',
'а это вторник',
'конечно же среда',
'четверг',
'пятница - прямо после четверга',
'суббота, рабочая неделя окончена',
];
const getWeekdaysOfMonth = (year, month) => Array.from(
{ length: new Date(year, month--, 0).getDate() },
(n, i) => {
const d = new Date(year, month, i + 1);
return d.toLocaleString('ru-RU', {
month: 'long',
day: 'numeric',
}) + ', ' + weekdays[d.getDay()];
});
const weekdaysOfFebruary2021 = getWeekdaysOfMonth(2021, 2);
document.querySelector('.products__body').addEventListener('click', e => {
const item = e.target.closest('.card-preview__item');
if (item) {
e.preventDefault();
const { srcset } = item.querySelector('source');
item.closest('.card').querySelector('.card-head__image source').srcset = srcset;
}
});
For DOM trees which represent HTML documents, the returned tag name is always in the canonical upper-case form.
if(str.tagName == 'ul') {
} else if (str.tagName == 'li') {
str
, что за странный выбор имени? Там же элемент, а не строка.elem.append('li');
for (let el of strLi) { el.addEventListener('click',func); };
func
вынесено за пределы текущей функции, иначе бы при каждом клике всем существующим li
добавлялся новый обработчик.li
, на свежесозданных li
клик обрабатываться не будет (касается и тех, что изначально существуют).li
- так зачем назначать отдельный обработчик клика? То, что делаете в func
, вполне можно делать прямо тут.document.querySelector('ul').addEventListener('click', e => {
const t = e.target;
const ct = e.currentTarget;
t.insertAdjacentHTML('beforeend', ct === t ? '<li>text</li>' : '!');
});
const parent = document.querySelector('ul');
.parent.querySelectorAll(':scope > *').forEach(n => parent.prepend(n));
// или
Element.prototype.append.apply(parent, [...parent.children].reverse());
// или
const [ first, ...rest ] = parent.children;
first?.before(...rest.reverse());
// или
for (const n of parent.children) {
parent.insertBefore(n, parent.firstElementChild);
}
// или
for (let i = parent.children.length; i--;) {
parent.insertAdjacentElement('beforeend', parent.children[i]);
}
// или
const elems = Array.from(parent.children);
while (elems.length) {
parent.appendChild(elems.pop());
}
const first = '125';
const startWithFirst = arr.filter(n => first.includes(`${n}`[0]));
console.log(startWithFirst);
const first = [ 1, 2, 5 ];
const startWithFirst = arr.filter(n => first.includes(n / (10 ** (Math.log10(n) | 0)) | 0));
const first = /^[125]/;
const startWithFirst = arr.filter(n => first.test(n));