var arr = ['Car', 'Car', 'Truck', 'Boat', 'Truck'];
var hist = {};

法一:

arr.map((a) => {
    if (a in hist) {
        hist[a]++;
    } else {
        hist[a] = 1;
    }
});

法二:

hist = arr.reduce((prev, item) => {
    if (item in prev) {
        prev[item]++
    } else {
        prev[item] = 1
    }
    return prev;
}, {});

输出:

console.log(hist);
// { Car: 2, Truck: 2, Boat: 1 }

参见:javascript-group-by-array


l1xnan
549 声望19 粉丝

每天进步一点点……