慕尼黑的夜晚无繁华
厌倦了看到所有使用for循环或jQuery的坏例子。Javascript现在拥有完美的工具:排序,映射和缩小。Uniq在保持现有订单的同时减少var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];var uniq = names.reduce(function(a,b){ if (a.indexOf(b) < 0 ) a.push(b); return a; },[]);console.log(uniq, names) // [ 'Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Carl' ]// one linerreturn names.reduce(function(a,b){if(a.indexOf(b)<0)a.push(b);return a;},[]);更快的uniq与排序可能有更快的方法,但这个很不错。var uniq = names.slice() // slice makes copy of array before sorting it .sort(function(a,b){ return a > b; }) .reduce(function(a,b){ if (a.slice(-1)[0] !== b) a.push(b); // slice(-1)[0] means last item in array without removing it (like .pop()) return a; },[]); // this empty array becomes the starting value for a// one linerreturn names.slice().sort(function(a,b){return a > b}).reduce(function(a,b){if (a.slice(-1)[0] !== b) a.push(b);return a;},[]);2015年更新:ES6版本:在ES6中,你有集合和传播,这使得删除所有重复项非常容易和高效:var uniq = [ ...new Set(names) ]; // [ 'Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Carl' ]根据事件排序:有人询问是根据有多少个唯一名称来排序结果:var names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']var uniq = names .map((name) => { return {count: 1, name: name} }) .reduce((a, b) => { a[b.name] = (a[b.name] || 0) + b.count return a }, {})var sorted = Object.keys(uniq).sort((a, b) => uniq[a] < uniq[b])console.log(sorted)