javascript - 数组里有对象,符合条件数值叠加
阿神
阿神 2017-04-11 10:56:16
[JavaScript讨论组]
阿神
阿神

闭关修行中......

全部回复(3)
高洛峰

咦,这个我不是给你答过了么?:

修正:

好吧,那我们再来改一次试试:

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,真的不怎么简洁

天蓬老师

深度固定,属性固定。直接用for扫描一遍不就得了……
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就可以

console.log(res.sort(function (cur, next) {
  return cur.poll < next.poll
})[0])
// { code: '574417bc79df540065d92df7', poll: 18 }
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号