(str.match(/[0-9]+/g) ?? []).map(Number)
// или
Array.from(str.matchAll(/\d+/g), n => +n)
// или
str.split(/\D+/).filter(Boolean).map(parseFloat)
// или
eval(`[${str.replace(/\D+/g, (m, i) => i ? ',' : '')}]`)
// или
[...str].reduce((acc, n, i, a) => (
isNaN(n) || (isNaN(a[i - 1]) && acc.push(0), acc.push(n - 0 + acc.pop() * 10)),
acc
), [])
isValid() {
return Object.values(obj).flatMap(Object.values).every(n => n.valid);
},
objects() {
return Object.values(this.obj).flatMap(Object.values);
},
isValid() {
return this.objects.every(n => n.valid);
},
ищет метод toString - его нет
test.toString
, то результатом будет undefined
. Вы проверьте, так ли это. Будете удивлены. const tables = document.querySelectorAll('селектор таблиц');
for (const table of tables) {
const labels = Array.prototype.map.call(
table.querySelectorAll('thead th'),
th => th.innerText
);
for (const tbody of table.tBodies) {
for (const tr of tbody.rows) {
for (let i = 0; i < tr.cells.length; i++) {
tr.cells[i].setAttribute('data-label', labels[i]);
}
}
}
}
// или
tables.forEach(table => {
table.querySelectorAll('tbody td').forEach(function(td) {
td.dataset.label = this[td.cellIndex];
}, Array.from(table.tHead.rows[0].cells, th => th.textContent));
});
Задача проверить является ли список палиндромом, я делаю самое банальное, дан список head, я проверяю return head == head[: :-1]
каким образом в текущей реализации можно при клике на кнопку "назад" вернуть первоначальный вид массива pollLis
pollList
новое значение, старое вы теряете безвозвратно.pop
. Кнопка "назад" - блокировать или не отображать, если размер стека меньше двух.<router-link :to="`/Product/${item}`">{{ item }}</router-link>
const result = data
.flatMap(n => n.values)
.filter(n => n.Ids.some(m => arr.includes(m)))
.map(({ id, title }) => ({ id, title }));
const diff = (arr1, arr2, key = n => n) =>
arr1.filter(function(n) {
return !this.has(key(n));
}, new Set(arr2.map(key)));
const result = diff(allCass, defaultCass, n => n.id);
const Todos = ({ todos, TodoItem }) => (
<div className="todos">
{todos.map(n => (
<div className="todo-item" key={n.id}>
<TodoItem todo={n} />
</div>
))}
</div>
);
const HeaderTodoItem = ({ todo }) => (
<h3>{todo.title}</h3>
);
const AppTodoItem = ({ todo }) => (
<>
<img src={todo.img} alt={todo.title} />
<div>
<h3>{todo.title}</h3>
<p>{todo.text}</p>
</div>
</>
);
<Todos todos={todos} TodoItem={HeaderTodoItem} />
<Todos todos={todos} TodoItem={AppTodoItem} />
Пытался сделать через reduce из библиотеки lodash
const newArr = _.map(_.groupBy(arr, 'merch'), (v, k) => ({
merch: +k,
games: _.uniq(_.flatMap(v, 'games')),
}));
const newArr = Object
.entries(arr.reduce((acc, n) => ((acc[n.merch] ??= []).push(...n.games), acc), {}))
.map(n => ({ merch: +n[0], games: [...new Set(n[1])] }));
const SORT_FUNCS = {
priceAsc: (a, b) => a.price - b.price,
priceDesc: (a, b) => b.price - a.price,
formedAsc: (a, b) => a.formed_in - b.formed_in,
formedDesc: (a, b) => b.formed_in - a.formed_in,
};
const data = useMemo(() => {
const sortFunc = SORT_FUNCS[sortType];
return sortFunc ? [...bands].sort(sortFunc) : bands;
}, [ sortType ]);
const [ author, setAuthor ] = useState(null);
const [ dateMin, setDateMin ] = useState(null);
const [ dateMax, setDateMax ] = useState(null);
const authors = useMemo(
() => [...new Set(articles.map(n => n.author))],
[ articles ]
);
const filteredArticles = useMemo(
() => [
[ author, n => n.author === author ],
[ dateMin, n => n.publishedAt >= dateMin ],
[ dateMax, n => n.publishedAt <= dateMax ],
].reduce((acc, n) => n[0] ? acc.filter(n[1]) : acc, articles),
[ articles, author, dateMin, dateMax ]
);
<select value={author} onChange={e => setAuthor(e.target.value)}>
<option></option>
{authors.map(n => <option>{n}</option>)}
</select>
от <input type="date" value={dateMin} onChange={e => setDateMin(e.target.value)} />
до <input type="date" value={dateMax} onChange={e => setDateMax(e.target.value)} />
{filteredArticles.map(n => <Card {...n} />)}
data: () => ({
handle: null,
...
}),
mounted() {
const mql = matchMedia('(max-width: 768px)');
const onChange = () => this.handle = mql.matches ? '.image' : null;
onChange();
mql.addEventListener('change', onChange);
this.$on('hook:beforeDestroy', () => mql.removeEventListener('change', onChange));
},
<draggable
:options="{ handle, ... }"
...
>
computed: {
deadlineText() {
const today = new Date().setHours(0, 0, 0, 0);
const deadline = new Date(this.task.deadline).setHours(0, 0, 0, 0);
return [ 'Уже было', 'Сегодня', 'Жди' ][1 + Math.sign(deadline - today)];
},
},
const [ autoplay, setAutoplay ] = useState(false);
const swiper = useRef();
useEffect(() => {
swiper.current.autoplay[autoplay ? 'start' : 'stop']();
}, [ autoplay ]);
<input
type="checkbox"
checked={autoplay}
onChange={e => setAutoplay(e.target.checked)}
/>
<Swiper
onSwiper={instance => swiper.current = instance}
...
>