gpt4 book ai didi

javascript - JS : Filter array of objects by max value per category

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:21 24 4
gpt4 key购买 nike

实现类似sql的过滤效果的最有效/最优雅的方法是什么。我想过滤它们并只获取在某些组中具有最大值的对象。

这是我的代码,它可以工作,但可能不是最好的方法:

uniqueValues = (arr) => [...new Set(arr)];
getMaxTimeOf = (arr) => Math.max(...arr.map(o => o.timeStamp), 0);
selectorName = (name) => (obj) => obj.name === name;
selectorTime = (time) => (obj) => obj.timeStamp === time;
getGroup = (obj, selector) => obj.filter(selector)

onlyLastChangedFrom = (history) => {
const uniqueNames = uniqueValues(history.map(o => o.name))
let filtered = []
uniqueNames.forEach(name => {
const group = getGroup(history, selectorName(name))
const groupLastTime = getMaxTimeOf(group)
const lastChange = getGroup(group, selectorTime(groupLastTime))
filtered.push(lastChange[0])
});
return filtered
}
onlyLastChangedFrom(history)
    // Input:
[ { name: 'bathroom',
value: 54,
timeStamp: 1562318089713 },
{ name: 'bathroom',
value: 55,
timeStamp: 1562318090807 },
{ name: 'bedroom',
value: 48,
timeStamp: 1562318092084 },
{ name: 'bedroom',
value: 49,
timeStamp: 1562318092223 },
{ name: 'room',
value: 41,
timeStamp: 1562318093467 } ]

// Output:
[ { name: 'bathroom',
value: 55,
timeStamp: 1562318090807 },
{ name: 'bedroom',
value: 49,
timeStamp: 1562318092223 },
{ name: 'room',
value: 41,
timeStamp: 1562318093467 } ]

最佳答案

Reduce数组到对象,使用 name 属性作为键。对于每个项目,检查累加器中存在的项目是否具有比当前项目更高的值,如果不是,则将其替换为当前项目。使用 Object.values() 转换回数组:

const arr = [{"name":"bathroom","value":54,"timeStamp":1562318089713},{"name":"bathroom","value":55,"timeStamp":1562318090807},{"name":"bedroom","value":48,"timeStamp":1562318092084},{"name":"bedroom","value":49,"timeStamp":1562318092223},{"name":"room","value":41,"timeStamp":1562318093467}]

const result = Object.values(arr.reduce((r, o) => {
r[o.name] = (r[o.name] && r[o.name].value > o.value) ? r[o.name] : o

return r
}, {}))

console.log(result)

关于javascript - JS : Filter array of objects by max value per category,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56901732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com