const index = arr.findIndex(n => n.id === newObj.id);
if (index !== -1) {
arr[index] = newObj;
} else {
arr.push(newObj);
}
const obj = arr.find(n => n.id === newObj.id);
if (obj) {
Object.assign(obj, newObj);
} else {
arr.push(newObj);
}
stuff.map(n => `${n.firstName} ${n.lastName}`).sort((a, b) => a.localeCompare(b))
$('селектор родительских элементов инпутов')
.last()
.clone()
.find('input')
.attr('name', (i, name) => name.replace(/(?<=\[)\d+(?=\])/, m => +m + 1))
.end()
.appendTo('кому-то там добавляется, сами разберётесь кому');
На IOS не работает (safari)
name.replace(/\[(\d+)\]/, (m, g1) => `[${+g1 + 1}]`)
const groupedPosts = Object.values(data.reduce((acc, n) => (
(acc[n.id] ??= []).push(n),
acc
), {}));
const button = document.querySelector('button');
button.addEventListener('click', showPosts);
const SHOW_POSTS_GROUPS = 2;
for (let i = 0; i < SHOW_POSTS_GROUPS; i++) {
showPosts();
}
function showPosts() {
const posts = groupedPosts.shift();
if (posts) {
const html = `<ul>${posts.map(n => `<li>${n.name}</li>`).join('')}</ul>`;
document.querySelector('.card__wrap').insertAdjacentHTML('beforeend', html);
button.disabled = !groupedPosts.length;
}
}
const interval = [ 0, 150 ];
const $slider = $('#storlekslider').slider({
range: 'max',
min: interval[0],
max: interval[1],
step: 1,
slide: (e, ui) => update(ui.value),
});
const $input = $('#storlek_testet').on('input', e => update(e.target.value));
$('button').click(e => update(+$input.val() + 50 * ($(e.target).text() === '+' ? 1 : -1)));
function update(val) {
val = Math.max(interval[0], Math.min(interval[1], val));
$input.val(val);
$slider.slider('value', val).find('.ui-slider-handle').text(val);
}
mounted() {
this.$el.querySelectorAll('input').forEach(n => n.dispatchEvent(new Event('input')));
},
inheritAttrs: false,
model: {
prop: 'checked',
},
props: [ 'value', 'checked' ],
computed: {
innerChecked: {
get() {
return this.checked;
},
set(val) {
this.$emit('input', val);
},
},
},
<label>
<input
type="checkbox"
v-model="innerChecked"
v-bind="$attrs"
:value="value"
>
<slot></slot>
</label>
data: () => ({
items: [
{ label: 'hello, world!!', value: 69 },
{ label: 'fuck the world', value: 187 },
{ label: 'fuck everything', value: 666 },
],
checked: [ 187 ],
}),
watch: {
checked(val) {
if (val.length > 1) {
this.checked = val.slice(-1);
}
},
},
<v-checkbox
v-for="n in items"
v-model="checked"
:value="n.value"
name="items[]"
>
{{ n.label }}
</v-checkbox>
const processNonEmptyObjectOnly = (f, defaultResult) =>
data => (
data = data instanceof Object ? Object.entries(data) : [],
data.length ? f(data) : defaultResult
);
const createTreeHTML = processNonEmptyObjectOnly(data => `
<ul>${data.map(n => `
<li>
${n[0]}
${createTreeHTML(n[1])}
</li>`).join('')}
</ul>`
, '');
document.body.insertAdjacentHTML('beforeend', createTreeHTML(data));
const createTreeElement = processNonEmptyObjectOnly(data =>
data.reduce((ul, n) => (
ul.append(document.createElement('li')),
ul.lastChild.append(n[0], createTreeElement(n[1])),
ul
), document.createElement('ul'))
, '');
document.body.append(createTreeElement(data));
computed: {
range() {
const prices = this.filterData.map(n => n.price);
return {
min: Math.min(...prices),
max: Math.max(...prices),
};
},
// или
range() {
return this.filterData.reduce(({ min, max }, { price: n }) => ({
min: min < n ? min : n,
max: max > n ? max : n,
}), { min: Infinity, max: -Infinity });
},
// или
range() {
const prices = this.filterData.map(n => n.price).sort((a, b) => a - b);
return {
min: prices[0] ?? Infinity,
max: prices[prices.length - 1] ?? -Infinity,
};
},
},
<input type="range" v-bind="range">
Note: This API has been removed in jQuery 3.0; please use.on( "load", handler )
instead of.load( handler )
and.trigger( "load" )
instead of.load()
const grouped = Object.entries(arr.reduce((acc, n) => (
(acc[n.id] ??= []).push(n.name),
acc
), {}));
document.body.insertAdjacentHTML('beforeend', grouped
.map(([ k, v ]) => `
<ul id="list-${k}">${v.map(n => `
<li>${n}</li>`).join('')}
</ul>`)
.join('')
);
document.body.append(...grouped.map(([ id, names ]) => {
const ul = document.createElement('ul');
ul.id = `list-${id}`;
ul.append(...names.map(n => {
const li = document.createElement('li');
li.textContent = n;
return li;
}));
return ul;
}));
str.replace(/\d{3}-\d{2}/, '***-**')
// или
str.slice(0, 9) + '***-**' + str.slice(15)
// или
str.replace(/\d(?=\d*-)/g, '*')
// или
str.replace(/\d+(?=-)/g, m => '*'.repeat(m.length))
// или
str.replace(/(?<=\) ).{6}/, '***-**')
// или
str.match(/^.{9}|.{3}$/g).join('***-**')
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>
.