js 一维数组查询和数值相加

oneplus
  • 788

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
    }
]
回复
阅读 3.1k
3 个回答
✓ 已被采纳

题主表意不明。

如果是一维数组的话:

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');

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
宣传栏