//实用场景一(数组去重)注意:先排序
var arr = [1, 2, 1, 2, 3, 4, 5, 7, 7, 7, 7, 7, 8, 8, 9, 9]; var result = arr.sort().reduce((init, current) => { if (init.length === 0 || init[init.length - 1] !== current) { init.push(current); } return init; }, []); console.log(JSON.stringify(arr)); console.log(JSON.stringify(result));
//实用场景二 (计算数组中每个元素出现的个数)
var arr = ['Tom', 'Jerry', 'Tom', 'Mike', 'Mike', 'Bolp']; var new_arr = arr.reduce(function(result, value) { if (value in result) { result[value]++; } else { result[value] = 1; } return result; }, {}); console.log(new_arr);