javascript - js 一维数组查询和数值相加
天蓬老师
天蓬老师 2017-04-11 10:35:44
0
3
1088

1.判断 var uid ="5744242bc4c971005d5ff04e" 是否存在数组中,php有 in_array() 函数,js有比较方便的吗?
2.指定的uid 数组中的数值相加。
有没有不通过遍历的方式得到结果或者最简便的方式?

[
    {
        "uid": "5744242bc4c971005d5ff04e",
        "num": 40,
        "time": 1464150797000
    },
    {
        "uid": "5744242bc4c971005d5ff04e",
        "num": 12,
        "time": 1464251797000
    },
    {
        "uid": "574424e5df0eea0063adefc6",
        "num": 10,
        "time": 1464152873000
    }
]
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
Ty80

题主表意不明。

如果是一维数组的话:

var sum = function (input, uid) {
    return input.filter(function (i) { return i.uid === uid; }).reduce(function (f, s) { return f.num + s.num; });
};

sum([{"uid":"5744242bc4c971005d5ff04e","num":40,"time":1464150797000},{"uid":"5744242bc4c971005d5ff04e","num":12,"time":1464251797000},{"uid":"574424e5df0eea0063adefc6","num":10,"time":1464152873000}], '5744242bc4c971005d5ff04e');

如果是要按照题目中的二维数组,对于出现了指定 uid 的子数组分别进行求和的话:

var sum = function (input, uid) {
    return input.filter(function (i) { return i.some(function (s) { return s.uid === uid; }); }).map(function (i) { return i.reduce(function (f, s) { return f + s.num; }, 0); });
};

sum([[{"uid":"5744242bc4c971005d5ff04e","num":40,"time":1464150797000}],[{"uid":"5744242bc4c971005d5ff04e","num":12,"time":1464251797000}],[{"uid":"574424e5df0eea0063adefc6","num":10,"time":1464152873000}]], '5744242bc4c971005d5ff04e');
刘奇

你的需求和这个很像,你们是同学么?

https://segmentfault.com/q/1010000005330302/a-1020000005330807

需要检查数组中所有内容,不遍历怎么行?不过如果使用 map,可以加速循环体中的检索过程,具体实现你可以参考上面的链接

小葫芦

1.

var a = [
    {
        "uid": "5744242bc4c971005d5ff04e",
        "num": 40,
        "time": 1464150797000
    },
    {
        "uid": "5744242bc4c971005d5ff04e",
        "num": 12,
        "time": 1464251797000
    },
    {
        "uid": "574424e5df0eea0063adefc6",
        "num": 10,
        "time": 1464152873000
    }
]
b = a.find( i => i.uid == '5744242bc4c971005d5ff04e');
console.log(b)
// Object {uid: "5744242bc4c971005d5ff04e", num: 40, time: 1464150797000}

2.

var a = [
    {
        "uid": "5744242bc4c971005d5ff04e",
        "num": 40,
        "time": 1464150797000
    },
    {
        "uid": "5744242bc4c971005d5ff04e",
        "num": 12,
        "time": 1464251797000
    },
    {
        "uid": "574424e5df0eea0063adefc6",
        "num": 10,
        "time": 1464152873000
    }
]
a.filter(i => i.uid == '5744242bc4c971005d5ff04e').reduce((prev, curr) => (prev.num || prev) + curr.num);
// 52
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template