Legendary

李洋的学习笔记


js数组去重

<p>1.Array.from与set去重(推荐):</p> <pre><code>function unique(arr) { if (!Array.isArray(arr)) { console.log('type error!') return } return Array.from(new Set(arr)) } </code></pre> <ol> <li>set与解构赋值去重(与方法一类似): <pre><code>function unique(arr) { if (!Array.isArray(arr)) { console.log('type error!') return } return [...new Set(arr)] }</code></pre></li> <li>利用对象属性(唯一)去重: <pre><code>function unique(arr) { if (!Array.isArray(arr)) { console.log('type error!') return } let res = [], obj = {} for (let i = 0; i &lt; arr.length; i++) { if (!obj[arr[i]]) { res.push(arr[i]) obj[arr[i]] = 1 } else { obj[arr[i]]++ } } return res }</code></pre></li> <li>相邻元素去重(排序=&gt;去重) <pre><code>function unique(arr) { if (!Array.isArray(arr)) { console.log('type error!') return } arr = arr.sort() let res = [] for (let i = 0; i &lt; arr.length; i++) { if (arr[i] !== arr[i-1]) { res.push(arr[i]) } } return res }</code></pre></li> </ol> <p>5.json数组去重:</p> <pre><code>arr = [ {'name':'li'}, {'name':'li'}, {'age':'20'} ] var hash = {}; arr = arr.reduce(function(item, next) { hash[next.name] ? '' : hash[next.name] = true &amp;&amp; item.push(next); return item }, []) console.log(arr)</code></pre>

页面列表

ITEM_HTML