1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | function array_count_values (array) { const tmp_arr = {}; let key = ''; const __countValue = function (value) { switch (typeof(value)) { case 'number': if (Math.floor(value) !== value) { return; } break; case 'string': if (value in this && this.hasOwnProperty(value)) { ++this[value]; } else { this[value] = 1; } break; } }; if (typeof array === 'object') { for (key in array) { if (array.hasOwnProperty(key)) { __countValue.call(tmp_arr, array[key]); } } } return tmp_arr; } // 결과 var test = [1, 1, 2, 2, 2, 3, 4]; console.log( array_count_values(test) ); { '1': 2, '2': 3, '3': 1, '4': 1 } | cs |
'개발 > script' 카테고리의 다른 글
[javascript] 배열 키값 가져오기 (0) | 2018.04.12 |
---|