如何只筛选每种类型的项目



给定一个对象数组,如

[
{name: "john", power: 1},
{name: "john", power: 129391},
{name: "john", power: 91},
{name: "philip", power: 33},
{name: "philip", power: 883},
{name: "philip", power: 3112333},
]

我只想得到每个name中的一个项目——power最多的项目。结果是:

{name: "john", power: 129391},
{name: "philip", power: 3112333},

我只是不知道如何过滤每一个。我可以筛选具有相同名称但不具有不同名称的项目items.filter(item => item.name === 'john')

我想的一件事是将这些项与已经在结果数组中但尚未找到访问结果数组的方法的项进行比较。

尝试减少

const data = [
{name: "john", power: 1},
{name: "john", power: 129391},
{name: "john", power: 91},
{name: "philip", power: 33},
{name: "philip", power: 883},
{name: "philip", power: 3112333},
]
const powerUsersObj = data.reduce((acc,cur) => {
acc[cur.name] = acc[cur.name] ? Math.max(acc[cur.name],cur.power) : cur.power
return acc
},{})
console.log(powerUsersObj)
const powerUsersArr = Object.entries(powerUsersObj).map(entry => ({name:entry[0],power:entry[1]}))
console.log(powerUsersArr)

遍历第一个数组并累积要保存在另一个数组中的唯一键。然后再次遍历,在每个唯一密钥的基础上进行您想要的检查(在此密钥中比较power):

let input = [
{ name: "john", power: 1 },
{ name: "john", power: 129391 },
{ name: "john", power: 91 },
{ name: "philip", power: 33 },
{ name: "philip", power: 883 },
{ name: "philip", power: 3112333 },
];
let uniqueKeys = input
.map((e) => e.name)
.filter((key, i) => input.findIndex((e) => e.name === key) === i);
let output = uniqueKeys.map(
(key) =>
input
.filter((e) => e.name === key)
.sort((entryA, entryB) => entryB.power - entryA.power)[0]
);

使用一些字典或映射来跟踪旧的选择,并在迭代时根据需要替换项。

var arr = [
{name: "john", power: 1},
{name: "john", power: 129391},
{name: "john", power: 91},
{name: "philip", power: 33},
{name: "philip", power: 883},
{name: "philip", power: 3112333},
]
var selectedItems = {}
arr.forEach(item => {
const key = item.name;
if(selectedItems[key] && selectedItems[key].power < item.power) {
selectedItems[key] = item
} else if(!selectedItems[key]) {
selectedItems[key] = item
}
});
console.log(Object.values(selectedItems))

您应该使用reduce函数

const  table = [
{name: "john", power: 1},
{name: "john", power: 129391},
{name: "john", power: 91},
{name: "philip", power: 33},
{name: "philip", power: 883},
{name: "philip", power: 3112333},
]
const result = [...table.reduce((r, o) => {
const key = o.name;
const item = r.get(key) || Object.assign({ name: o.name }, {power: 0});
item.power = o.power>item.power? o.power: item.power;
return r.set(key, item);
}, new Map).values()]


console.log(result);

相关内容

  • 没有找到相关文章

最新更新