(str.match(/[0-9]+/g) ?? []).map(Number)
// или
Array.from(str.matchAll(/\d+/g), n => +n)
// или
(function get(arr, i, n = arr[i]) {
return i < arr.length
? (n ? [ parseInt(n) ] : []).concat(get(arr, -~i))
: [];
})(str.split(/[^\d]+/), 0)
// или
eval(`[${str.replace(/\D+/g, (m, i) => i ? ',' : '')}]`)
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 { tHead, tBodies } of tables) {
const labels = Array.prototype.map.call(
tHead.rows[0].cells,
th => th.textContent
);
for (const { rows } of tBodies) {
for (const { cells } of rows) {
for (const [ i, label ] of labels.entries()) {
cells[i].dataset.label = label;
}
}
}
}tables.forEach(table => {
table.querySelectorAll('tbody td').forEach(function(td) {
td.setAttribute('data-label', this[td.cellIndex]);
}, Array.from(table.querySelectorAll('thead th'), th => th.innerText));
});
Задача проверить является ли список палиндромом, я делаю самое банальное, дан список head, я проверяю return head == head[: :-1]
const getPrimitives = data =>
data instanceof Object
? Object.values(data).flatMap(getPrimitives)
: [ data ];
const result = getPrimitives(obj).map(value => ({ value }));function* getPrimitives(data) {
if (data instanceof Object) {
for (const k in data) if (Object.hasOwn(data, k)) {
yield* getPrimitives(data[k]);
}
} else {
yield data;
}
}
const result = Array.from(getPrimitives(obj), n => ({ value: n }));function getNestedData(data, test, getter = n => n) {
const result = [];
for (const stack = [ data ]; stack.length;) {
const n = stack.pop();
if (n instanceof Object) {
stack.push(...Object.values(n).reverse());
}
if (test(n)) {
result.push(getter(n));
}
}
return result;
}
const resutl = getNestedData(obj, n => n !== Object(n), n => ({ value: n }));
<router-link :to="`/Product/${item}`">{{ item }}</router-link>
const unique = function*(data, keys = n => n) {
const picked = new Map;
for (const n of data) {
const p = []
.concat(keys(n))
.reduce((acc, k) => acc.set(k, acc.get(k) ?? new Map).get(k), picked);
if (!p.set(this, p.has(this)).get(this)) {
yield n;
}
}
}.bind(Symbol());// собираем новый массив
const newArr = Array.from(unique(arr, n => [ n.name, n.value ]));
// обновляем существующий
arr.splice(0, arr.length, ...unique(arr, Object.values));
const result = data
.flatMap(n => n.values)
.filter(n => n.Ids.some(m => arr.includes(m)))
.map(({ id, title }) => ({ id, title }));const inArr = Set.prototype.has.bind(new Set(arr));
const data.reduce((acc, { values }) => (
values.forEach(({ Ids, ...n }) => Ids.some(inArr) && acc.push(n)),
acc
), []);
const result = allCass.filter(function(n) {
return !this.has(n.id);
}, new Set(defaultCass.map(n => n.id)));function* diff(data1, data2, key = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const keys = new Set;
for (const n of data2) {
keys.add(getKey(n));
}
for (const n of data1) {
if (!keys.has(getKey(n))) {
yield n;
}
}
}const result = [...diff(allCass, defaultCass, 'id')];Array.from(diff('abcdE', 'AcD', n => n.toLowerCase())) // ['b', 'E']for (const n of diff(Array(8).keys(), Array(5).keys())) {
console.log(n); // 5 6 7
}
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 = [
[ 'без сортировки' ],
[ 'цена, по возрастанию', (a, b) => a.price - b.price ],
[ 'цена, по убыванию', (a, b) => b.price - a.price ],
[ 'год создания, по возрастанию', (a, b) => a.formed_in - b.formed_in ],
[ 'год создания, по убыванию', (a, b) => b.formed_in - a.formed_in ],
];const [ sortType, setSortType ] = useState(0);
const data = useMemo(() => {
const sortFunc = SORT[sortType][1];
return sortFunc ? [...bands].sort(sortFunc) : bands;
}, [ bands, sortType ]);<select value={sortType} onChange={e => setSortType(e.target.value)}>
{SORT.map((n, i) => <option value={i}>{n[0]}</option>)}
</select>
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, ... }"
...
>
arr.sort((a, b) => a.surname.localeCompare(b.surname) || a.name.localeCompare(b.name));const sorted = (arr, keys) => arr
.map(n => [ n ].concat(keys(n)))
.sort((a, b) => {
let diff = 0;
a.find((n, i) => diff = i && ((n < b[i]) ? -1 : +(n > b[i])));
return diff;
})
.map(n => n[0]);
const sortedArr = sorted(arr, n => [ n.surname.toLowerCase(), n.name.toLowerCase() ]);
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)];
},
},