扫码关注官方订阅号
闭关修行中......
咦,这个我不是给你答过了么?:
修正:
好吧,那我们再来改一次试试:
var res = results .reduce(function(p, item) { p.push.apply(p, item.data); return p; }, []) .reduce(function(p, item) { var filters = p.filter(function(data) { return data.code === item.code; }); if (filters.length === 0) { p.push(item); } else { filters[0].poll += item.poll; } return p; }, []); console.log(res); var max = res .reduce(function(p, item) { if (p.poll < item.poll) { return item; } return p; }, {poll: 0}); console.log(max); //你想要的结果: { code: '574417bc79df540065d92df7', poll: 18 }
当然我这般似乎不用ES6,真的不怎么简洁
ES6
深度固定,属性固定。直接用for扫描一遍不就得了……ans就是所求。
ans
const map = {}; let max = 0, ans; for(let i = 0; i < results.length; i++) { for(let j = 0; j < results[i].data.length; j++) { map[results[i].data[j].code] = map[results[i].data[j].code] ? map[results[i].data[j].code] + results[i].data[j].poll : results[i].data[j].poll; if(map[results[i].data[j].code] > max) { max = map[results[i].data[j].code]; ans = results[i].data[j].code; } } }
@leftstick 既然res是个数组,用sort就可以
res
sort
console.log(res.sort(function (cur, next) { return cur.poll < next.poll })[0]) // { code: '574417bc79df540065d92df7', poll: 18 }
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
咦,这个我不是给你答过了么?:
修正:
好吧,那我们再来改一次试试:
当然我这般似乎不用
ES6,真的不怎么简洁深度固定,属性固定。直接用for扫描一遍不就得了……
ans就是所求。@leftstick 既然
res是个数组,用sort就可以