[js] 过滤连续重复的元素
#
var uniqueInOrder = function(iterable) { if (iterable instanceof Array) { var temp = []; for (var i = 0; i < iterable.length; i++) { if (iterable[i] !== iterable[i + 1]) { temp.push(iterable[i]); } } return temp; } if (typeof iterable === 'string') { var temp = ''; for (var i = 0; i < iterable.length; i++) { if (iterable[i] !== iterable[i + 1]) { temp += iterable[i]; } } return temp.split(''); } } var uniqueInOrder = function(iterable) { if (Array.isArray(iterable)) { return iterable.filter((v, i) => v !== iterable[i + 1]); } if (typeof iterable === 'string') { var iterable = iterable.split(''); return iterable.filter((v, i) => v !== iterable[i + 1]) } } var uniqueInOrder = function(iterable) { return [].filter.call(iterable, (function(a, i) { return iterable[i - 1] !== a })); } var uniqueInOrder = function(iterable) { return Array.prototype.reduce.call(iterable, function(a, b) { if (a[a.length - 1] !== b) a.push(b); return a; }, []); } console.log(uniqueInOrder([1, 2, 2, 3, 3])); console.log(uniqueInOrder('AAAABBBCCDAABBB')); console.log(uniqueInOrder('ABBCcAD'));