javascript – 取出陣列(物件)中,元素重複的次數
透過透過 forEach 計算呼叫的次數來完成,如果呼叫存在,那就 +1。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
var collectionRepeat = function(box, key){ var counter = {}; box.forEach(function(x) { counter[x] = (counter[x] || 0) + 1; }); var val = counter[key]; if (key === undefined) { return counter; } return (val) === undefined ? 0 : val; } var ary = ['a', 'b', 'a', 'c', 'b', 'd', 'a', 'e']; console.log(collectionRepeat(ary)); // Object { a: 3, b: 2, c: 1, d: 1, e: 1 } console.log(collectionRepeat(ary, 'a')); // => 3 console.log(collectionRepeat(ary, 'b')); // => 2 console.log(collectionRepeat(ary, 'c')); // => 1 console.log(collectionRepeat(ary, 'z')); // => 0 |