JavaScript数组中包含数组如何去重?

例如说[1,2,3,[1,1,2],[3,2],2]这样的应该如何去掉重复的数字,谢谢

临摹微笑
浏览 1454回答 5
5回答

宝慕林4294392

var arr = [1,2,3,[1,1,2],[3,2],2];var result = arr.reduce(function(v, i) {&nbsp; &nbsp; if (Array.isArray(i)) {&nbsp; &nbsp; &nbsp; &nbsp; i.forEach(function(item) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (v.indexOf(item) < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v.push(item);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; } else {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (v.indexOf(i) < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v.push(i);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return v;}, []);console.log(result);

哔哔one

Array.prototype.unique = function(){&nbsp; &nbsp; var res = [];&nbsp; &nbsp; var json = {};&nbsp; &nbsp; for(var i = 0; i < this.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; if(!json[this[i]]){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.push(this[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; json[this[i]] = 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return res;}var arr = [112,1,23,'absc'];alert(arr.unique());1.创建一个新的数组存放结果2.创建一个空对象3.for循环时,每次取出一个元素与对象进行对比,如果这个元素不重复,则把它存放到结果数组中,同时把这个元素的内容作为对象的一个属性,并赋值为1,存入到第2步建立的对象中。来自

侃侃无极

一维数组的话,简洁的写法应该是这样的myArray.filter(function(elem,&nbsp;pos,self){return&nbsp;self.indexOf(elem)==&nbsp;pos;})

开心每一天1111

下面的做法局限性很大, Just for fan.arr.toString().split(",").sort().reduce(function(v,i){if&nbsp;(v.indexOf(i)&nbsp;<&nbsp;0)&nbsp;{v.push(i);}&nbsp;return&nbsp;v;&nbsp;},&nbsp;[]). map(function(element){return&nbsp;parseInt(element,10);});

Helenr

思路是合并子项,再用Set去重即可const data = [1,2,3,[1,1,2],[3,2],2];const unique = [...new Set(data.reduce((p, vo) => p.concat(vo), []))];
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript