js通过递归实现数组去重
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22Array.prototype.distinct = function () { var arr = this, len = arr.length; arr.sort(function (a, b) { //对数组进行排序才能方便比较 return a - b; }) function loop(index) { if (index >= 1) { if (arr[index] === arr[index - 1]) { arr.splice(index, 1); } loop(index - 1); //递归loop函数进行去重 } } loop(len - 1); return arr; }; var a = [1, 2, 3, 4, 5, 6, 5, 3, 2, 4, 56, 4, 1, 2, 1, 1, 1, 1, 1, 1, 56, 45, 56]; var b = a.distinct(); console.log(b.toString()); //1,2,3,4,5,6,45,56
题解思路:
- 先对数组进行排序。这样会把所有的相同的元素排在一起
- 然后通过递归方法前后比对,查看是否相同。
- 如果元素值相同,那么就需要splice删除,但是注意数组索引的塌陷。
最后
以上就是能干小松鼠最近收集整理的关于js通过递归实现数组去重的全部内容,更多相关js通过递归实现数组去重内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复