// есть вариант применить рекурсию
const flatTree = (tree, childrenKey) =>
(tree instanceof Array ? tree : []).reduce((acc, n) => (
acc.push(n, ...flatTree(n[childrenKey], childrenKey)),
acc
), []);
// а можно обойтись и без неё
const flatTree = function*(tree, childrenKey) {
const stack = [];
for (let [ i, arr ] = this(tree); ++i < arr.length || stack.length;) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else {
yield arr[i];
stack.push([ i, arr ]);
[ i, arr ] = this(arr[i][childrenKey]);
}
}
}.bind(x => [ -1, Array.isArray(x) ? x : [] ]);
v-for
по его значению:computed: {
users() {
// если использовать обычную функцию
return flatTree(this.elements, 'children');
// или, генератор
return [...flatTree(this.elements, 'children')];
},
},
<option v-for="n in users" :key="n.id">{{ n.name }}</option>
<gmap-map
ref="map"
...
const bounds = new google.maps.LatLngBounds();
массивКоординатВашихЛокаций.forEach(n => bounds.extend(n));
this.$refs.map.fitBounds(bounds);
const mul = arr =>
arr.reduce((acc, n) => acc * n, 1);
// или
const mul = arr =>
eval(arr.join('*')) ?? 1;
// или
function mul(arr) {
let result = 1;
for (const n of arr) {
result *= n;
}
return result;
}
// или
function mul(arr) {
let result = 1;
for (let i = 0; i < arr.length; i++) {
result = result * arr[i];
}
return result;
}
// или
const mul = (arr, i = 0) =>
i < arr.length
? arr[i] * mul(arr, -~i)
: 1;
const result = count.map(function(n) {
return mul(data.slice(this[0], this[0] += n));
}, [ 0 ]);
const result = count.map(n => mul(data.splice(0, n)));
function combine(a = {}, b = {}, c = {}) {
const combine = (...arr) => arr
.flatMap(Object.entries)
.reduce((acc, [ k, v ]) => (acc[k] = (acc[k] ?? 0) + v, acc), {});
function combine() {
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 mostFrequentNum = Array
.from(arr.reduce((acc, n) => acc.set(n, -~acc.get(n)), new Map))
.reduce((max, n) => max[1] > n[1] ? max : n, [ , 0 ])
.at(0);
const mostFrequentNum = Object
.entries(arr.reduce((acc, n) => (acc[n] = (acc[n] ?? 0) + 1, acc), {}))
.reduce((acc, n) => (acc[n[1]] = +n[0], acc), [])
.pop();
не хочу дублировать код в v-slot:fastFilters, но как мне сделать так, чтоб по определенному флагу на фильтрах он появлялся и в fastFilters
<toolbar>
<slot name="fastFilters">
<slot name="filters" v-if="а здесь ваш флаг">
</toolbar>
<div class="filters">
<slot name="filters">
</div>
let [0: [fruit1, fruit2, fruit3]] = arr; //Uncaught SyntaxError: Invalid destructuring assignment target
const arr = [
[ 1, 2, 3 ],
[ 5, 6, 7 ],
[ 7, 8, 9 ],
];
const [ , [ , val1 ], [ ,, val2 ] ] = arr;
console.log(val1, val2); // 6 9
const arr = [
[ 1, 2, 3 ],
[ 5, 6, 7 ],
[ 7, 8, 9 ],
];
const { 1: { 1: val1 }, 2: { 2: val2 } } = arr;
console.log(val1, val2); // 6 9
props: {
modelValue: {
type: String,
default: '',
},
},
emits: [ 'update:modelValue' ],
setup(props, { emit }) {
const value = ref('');
watchEffect(() => value.value = props.modelValue);
return {
value,
onInput: e => emit('update:modelValue', value.value = e.target.value),
};
},
<input :value="value" @input="onInput">
computed: {
cartTotalCost() {
return this.cart_data.reduce((acc, n) => acc + n.price * n.amount, 0);
},
...
Object.values(t).forEach(n => {
n.children?.sort((a, b) => (a.order - b.order) || a.name.localeCompare(b.name));
});
const square = n => n ** 2;
// или
const square = n => n * n;
// или
const square = n => Math.pow(n, 2);
arr.forEach((n, i, a) => a[i] = square(n));
// или
arr.splice(0, arr.length, ...arr.map(square));
// или
for (const [ i, n ] of arr.entries()) {
arr[i] = square(n);
}
// или
for (let i = 0; i < arr.length; i++) {
arr[i] = square(arr[i]);
}
Как мне изменить код, чтобы исправить ошибку?
const countries = Array.from({ length: 3 }, prompt);
new gridjs.Grid({
columns: [
'Code',
{ name: 'Flag', formatter: val => gridjs.html(`<img src="${val}">`) },
'Name',
'Capital',
'Population',
],
data: () => Promise.all(countries.map(n =>
fetch(`//restcountries.com/v3.1/name/${n}`)
.then(r => r.json())
.then(([ r ]) => [
r.altSpellings[0],
r.flags.png,
r.name.common,
r.capital[0],
r.population,
])
.catch(() => [ ,,`${n} - это не страна`,, ])
)),
}).render(document.querySelector('#wrapper'));
(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(acc.pop() * 10 + n * 1)),
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);
},