const where = '.list';
const what = '.content';const $targets = $(where).children();
$(what).each((i, n) => $targets.eq(i).append(n));const targets = document.querySelector(where).children;
document.querySelectorAll(what).forEach((n, i) => targets[i]?.append(n));
Object.values(data).flat().find(n => n.title === search)Object.fromEntries(Object
.entries(data)
.map(n => [ n[0], n[1].filter(m => m.title.toLowerCase().includes(search.toLowerCase())) ])
.filter(n => n[1].length)
)
const result = Object.values(cars.reduce((acc, n) => (
(acc[n.make] ??= { make: n.make, attr: [] }).attr.push(n),
acc
), {}));function group(data, key, val = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const getVal = val instanceof Function ? val : n => n[val];
const result = new Map;
for (const n of data) {
const k = getKey(n);
result.set(k, result.get(k) ?? []).get(k).push(getVal(n));
}
return result;
}const result = Array.from(
group(cars, 'make'),
([ make, attr ]) => ({ make, attr })
);
str.slice(1, -1).split(', ')
// или
JSON.parse(str.replace(/[а-яё]+/g, '"$&"'))
// или
str.match(/[^\s\[\],]+/g) ?? []
coord.split(', ').map(Number)
// или
coord.match(/[\d.]+/g).map(n => +n)
// или
eval(`[${coord}]`)
// или
JSON.parse('['.concat(coord, ']'))
// или
Array.from(coord.matchAll(/[^, ]+/g), parseFloat)
const result = [...subcategory.reduce(
(acc, n) => (acc.get(n.category)?.children.push(n), acc),
new Map(category.map(n => [ n.id, { ...n, children: [] } ]))
).values()];const result = category.map(n => ({
...n,
children: subcategory.filter(m => m.category === n.id),
}));const result = category.map(function(n) {
return {
...n,
children: this[n.id] ?? [],
};
}, subcategory.reduce((acc, n) => ((acc[n.category] ??= []).push(n), acc), {}));
$('.item').on('mouseover', '.dot', function({ delegateTarget: t }) {
$('.thumb-target', t).attr('src', $(this).data('img'));
$('.dot', t).removeClass('select').filter(this).addClass('select');
});document.querySelectorAll('.item').forEach(n => {
n.addEventListener('mouseover', onMouseOver);
});
function onMouseOver({ target: t, currentTarget: ct }) {
const dot = t.closest('.dot');
if (dot) {
ct.querySelector('.thumb-target').src = dot.dataset.img;
ct.querySelectorAll('.dot').forEach(n => {
n.classList.toggle('select', n === dot);
});
}
}
const sum = (...arr) => arr
.flatMap(Object.entries)
.reduce((acc, [ k, v ]) => (
acc[k] = (acc[k] ?? 0) + v,
acc
), {});function sum() {
const result = {};
for (const n of arguments) {
for (const k in n) {
if (n.hasOwnProperty(k)) {
if (!result.hasOwnProperty(k)) {
result[k] = 0;
}
result[k] += n[k];
}
}
}
return result;
}const obj = sum(obj1, obj2);.
const container = document.querySelector('#element');
const itemSelector = '.someclass';
const key = 'id';
const attr = `data-${key}`;
const attrSelector = `[${attr}]`;container.querySelectorAll(itemSelector).forEach(function(n) {
n.addEventListener('click', this);
}, function(e) {
e.preventDefault();
let el = this;
while (!(el = el.parentNode).hasAttribute(attr)) ;
console.log(el.getAttribute(attr));
});container.querySelectorAll(attrSelector).forEach(n => {
n.addEventListener('click', onClick);
});
function onClick(e) {
if (e.target.matches(itemSelector)) {
e.preventDefault();
console.log(e.currentTarget.attributes[attr].value);
}
}container.addEventListener('click', e => {
const item = e.target.closest(itemSelector);
if (item) {
e.preventDefault();
console.log(item.closest(attrSelector).dataset[key]);
}
});
function sort(arr) {
const obj = Object.fromEntries(arr.map(n => [ n.parent, n ]));
const sorted = [];
for (let item = obj['null']; item; item = obj[item.id]) {
sorted.push(item);
}
return sorted;
}function sort(arr, parent = null) {
const item = arr.find(n => n.parent === parent);
return item
? [ item, ...sort(arr, item.id) ]
: [];
}
const formatDateStr = str =>
new Date(str.split(' GMT', 1)[0])
.toLocaleDateString('ru-RU')
.split('.')
.reverse()
.join(', ');const formatDateStr = function(str) {
const [ , month, day, year ] = str.match(/(\S+) (\d+) (\d+)/);
return [ year, this[month], day.padStart(2, 0) ].join(', ');
}.bind(Object.fromEntries(Array.from({ length: 12 }, (_, i) => [
new Date(0, i).toLocaleString('en', { month: 'short' }),
`${i + 1}`.padStart(2, 0)
])));
const includes = (arrs, search) =>
arrs.some(arr => arr.length === search.length && arr.every((n, i) => n === search[i]));function includes(arrs, search) {
COMPARE_ARRAYS:
for (const arr of arrs) {
if (arr.length === search.length) {
for (const [ i, n ] of arr.entries()) {
if (!Object.is(n, search[i])) {
continue COMPARE_ARRAYS;
}
}
return true;
}
}
return false;
}
const columns = [ '#', ...new Set(persons.flatMap(Object.keys)) ];
// или
const columns = [ '#' ].concat(Object.keys(Object.assign({}, ...persons)));document.body.insertAdjacentHTML('beforeend', `
<table>
<thead>
<tr>${columns.map(col => `
<th>${col}</th>`).join('')}
</tr>
</thead>
<tbody>${persons.map((person, i) => `
<tr>${columns.map((col, j) => `
<td>${j ? person[col] ?? '-' : i}</td>`).join('')}
</tr>`).join('')}
</tbody>
</table>
`);const table = document.createElement('table');
table.createTHead().insertRow().append(...columns.reduce((acc, col) => (
(acc[acc.length] = document.createElement('th')).textContent = col,
acc
), []));
persons.forEach(function(person, i) {
columns.forEach(function(col, j) {
this.insertCell().textContent = j ? person[col] ?? '-' : i;
}, this.insertRow());
}, table.createTBody());
document.body.append(table);
const find = (data, test, key) =>
test(key, data)
? data
: data === Object(data)
? Object.entries(data).reduce((found, n) =>
found !== null ? found : find(n[1], test, n[0])
, null)
: null;function find(data, test) {
for (const stack = [ [ , data ] ]; stack.length;) {
const [ k, v ] = stack.pop();
if (test(k, v)) {
return v;
} else if (v instanceof Object) {
stack.push(...Object.entries(v).reverse());
}
}
return null;
}const value = find(вложенный_объект, k => k === 'ключ');
const $section = $('.section').on('click', () => $section.addClass('opened'));
$section.find('.close').on('click', e => {
e.stopPropagation();
$section.removeClass('opened');
});
// или
const section = document.querySelector('.section');
section.addEventListener('click', () => section.classList.add('opened'));
section.querySelector('.close').addEventListener('click', e => (
e.stopPropagation(),
section.classList.remove('opened')
));const $section = $('section').click(e => {
$section.toggleClass('opened', !$(e.target).is('.close'));
});
// или
document.querySelector('.section').addEventListener('click', e => {
e.currentTarget.classList.toggle('opened', !e.target.matches('.close'));
});