3 回答
TA贡献1815条经验 获得超10个赞
你需要三张通行证
按想要的键和值分组
对数组进行排序
更新
prioritiey属性。
function groupBy(data, key, ...values) {
return Object.values(data.reduce((r, o) => {
r[o[key]] = r[o[key]] || { ...o, ...Object.fromEntries(values.map(k => [k, []])) };
values.forEach(k => r[o[key]][k].push(o[k]));
return r;
}, {}));
}
var list = [{ value: 'fox', country: 'nl', type: 'animal', priority: 1 }, { value: 'fox', country: 'be', type: 'animal', priority: 2 }, { value: 'cat', country: 'de', type: 'animal', priority: 3 }, { value: 'david', country: 'nl', type: 'human', priority: 4 }, { value: 'marc', country: 'be', type: 'human', priority: 5 }, { value: 'lola', country: 'de', type: 'human', priority: 6 }, { value: 'tiger', country: 'nl', type: 'animal', priority: 7 }, { value: 'koala', country: 'be', type: 'animal', priority: 8 }, { value: 'tiger', country: 'nl', type: 'animal', priority: 9 }],
result = groupBy(list, 'value', 'country')
.sort(({ type: a }, { type: b }) => a > b || -(a < b))
.map((priority => (o, i, { [i - 1]: p }) => {
if (p && p.type === o.type) ++priority;
else priority = 1;
return { ...o, priority };
})());
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1805条经验 获得超9个赞
如果值不存在,您需要检查该值是否存在,否则将新值推送到国家/地区数组。
var list = [
{ value: 'fox', country: 'nl', type: 'animal', priority: 1 },
{ value: 'fox', country: 'be', type: 'animal', priority: 2 },
{ value: 'cat', country: 'de', type: 'animal', priority: 3 },
{ value: 'david', country: 'nl', type: 'human', priority: 4 },
{ value: 'marc', country: 'be', type: 'human', priority: 5 },
{ value: 'lola', country: 'de', type: 'human', priority: 6 },
{ value: 'tiger', country: 'nl', type: 'animal', priority: 7 },
{ value: 'koala', country: 'be', type: 'animal', priority: 8 },
{ value: 'tiger', country: 'nl', type: 'animal', priority: 9 },
];
const l2 = list.reduce((accumulator, currentValue, index) => {
const {
country,
...value
} = currentValue;
const existing = accumulator
.find(item => item.value === currentValue.value);
if (existing) {
const {
countries
} = existing;
countries.push(country);
existing.countries = Array.from(new Set(countries))
} else {
accumulator.push({ ...value,
countries: [country]
});
}
return accumulator;
}, [])
console.log(l2)
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
TA贡献2036条经验 获得超8个赞
埃尔达的回答很好。只需在两次推送同一个国家之前添加国家检查。
我还用实际的列表项替换了扩展运算符,以保留它们的结构顺序。
const l2 = list.reduce((accumulator, currentValue) => {
const {
value,
country,
type,
priority
} = currentValue
const existing = accumulator
.find(item => item.value === currentValue.value)
if (existing) {
if (!(existing.countries.find(addedCountries => addedCountries === currentValue.country))) {
existing.countries.push(currentValue.country)
}
} else {
accumulator.push({ value,
countries: [country],
type,
priority
})
}
return accumulator
}, [])
添加回答
举报
