хочу, чтобы в переменной theme лежало значение state.theme, но по факту получается так: theme.theme
export const theme = (state = 'light', action) => {
switch (action.type) {
case constants.CHANGE_THEME:
return action.payload;
default:
return state;
}
};
const result = [...str].reduce((acc, n) => (acc[n] = (acc[n] ?? 0) + 1, acc), {});
function count(data, key = n => n) {
const counted = {};
for (const n of data) {
const k = key(n);
counted[k] = -~counted[k];
}
return counted;
}
const result = count(str);
const nums = [ -Infinity, -1, 0, 0, 0, 0, 69, 187, 666 ];
console.log(count(nums, Math.sign)); // {0: 4, 1: 3, -1: 2}
<div data-country="USA">New York</div>
<div data-country="USA">Boston</div>
<div data-country="USA">Las Vegas</div>
<div data-country="Japan">Osaka</div>
<div data-country="Japan">Tokyo</div>
<div data-country="Japan">Kyoto</div>
<div data-country="Japan">Yokohama</div>
<div data-country="Germany">Munich</div>
<div data-country="Germany">Dresden</div>
const cities = document.querySelectorAll('[data-country]');
console.log(count(cities, n => n.dataset.country)); // {USA: 3, Japan: 4, Germany: 2}
count(Array(9).keys(), n => [ 'чётные', 'нечётные' ][n & 1]) // {чётные: 5, нечётные: 4}
#elem
нового контента следует полностью перезаписывать его содержимое:document.querySelector('#elem').innerHTML = `
<table>${Array.from({ length: 2 }, (_, iRow) => `
<tr>${Array.from({ length: columns }, (_, iCol) => `
<td>${iRow + 1}.${iCol + 1}</td>`).join('')}
</tr>`).join('')}
</table>
`;
const table = document.createElement('table');
table.insertRow();
table.insertRow();
document.querySelector('#elem').append(table);
for (const n of table.rows) {
while (n.cells.length < columns) {
n.insertCell().textContent = `${-~n.rowIndex}.${n.cells.length}`;
}
while (n.cells.length > columns) {
n.lastElementChild.remove();
}
}
<input v-model.number="val">
watch: {
val(val) {
this.val = Math.max(1, val);
},
},
Как проверить, есть ли в массиве повторяющиеся элементы...
const hasDuplicates = arr.length > new Set(arr).size;
...и как записать эти элементы в новый массив...
// Получаем повторяющиеся элементы в единственном экземпляре
const duplicatedItemsUnique = Array.from(arr.reduce((acc, n) => (
acc[+acc[0].has(n)].add(n),
acc
), [ new Set, new Set ])[1]);
// Получаем все неуникальные элементы
const duplicatedItemsAll = arr.filter(function(n) {
return this.get(n) > 1;
}, arr.reduce((acc, n) => acc.set(n, -~acc.get(n)), new Map));
...или оставить только элементы которые повторяются?
arr.splice(0, arr.length, ...arr.filter(function(n) {
return this.get(n);
}, arr.reduce((acc, n) => acc.set(n, acc.has(n)), new Map)));
const containerSelector = '.lg-container';
const itemSelector = `${containerSelector} .lg-hotspot`;
const buttonSelector = `${itemSelector} .lg-hotspot__button`;
const activeClass = 'lg-hotspot--selected';
document.addEventListener('click', ({ target: t }) => {
const button = t.closest(buttonSelector);
const item = t.closest(itemSelector);
if (button) {
item.closest(containerSelector).querySelectorAll(itemSelector).forEach(n => {
n.classList[n === item ? 'toggle' : 'remove'](activeClass);
});
} else if (!item?.classList.contains(activeClass)) {
document.querySelectorAll(itemSelector).forEach(n => {
n.classList.remove(activeClass);
});
}
});
item.closest(containerSelector)
надо заменить на document
. export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
return character === '...' ? '...' : character;
const replacements = {
'...': '...',
'...': '...',
...
};
const newCharacters = characters.map(n => replacements[n] || n);
arr.flatMap(n => n.split(', ').map(Number))
`${arr}`.split(/\D+/).map(n => +n)
String(arr).match(/\d+/g).map(n => parseInt(n))
eval('[' + arr + ']')
JSON.parse('['.concat(arr, ']'))
$('.box-none', this).slideToggle(300);
$(this).find('.box-none').slideToggle(300);
document.querySelector('.copybox').addEventListener('click', ({ target: t }) => {
if (t.tagName === 'BUTTON') {
navigator.clipboard.writeText(t.previousElementSibling.textContent);
}
});
const groupedAndUnique = Object.entries(arr.reduce((acc, n) => {
(acc[n.category] = acc[n.category] ?? new Set).add(n.type);
return acc;
}, {}));
document.body.insertAdjacentHTML('beforeend', `
<ul>${groupedAndUnique.map(([ k, v ]) => `
<li>
${k}
<ul>${Array.from(v, n => `
<li>${n}</li>`).join('')}
</ul>
</li>`).join('')}
</ul>`
);
const ul = document.createElement('ul');
ul.append(...groupedAndUnique.map(([ header, items ]) => {
const li = document.createElement('li');
li.append(header, document.createElement('ul'));
for (const n of items) {
li.lastChild.append(document.createElement('li'));
li.lastChild.lastChild.textContent = n;
}
return li;
}));
document.body.append(ul);
$('.chosen-select')
.find(`option[data-value="${category}"]`)
.prop('selected', true)
.end()
.trigger('chosen:updated');