2024年11月js数组去重怎么操作?js数组去重的六个操作方法

 更新时间:2024-11-18

  ⑴方法二:利用indexOf以及forEach

  ⑵Array.prototype.distinct = function (){

  ⑶var arr = this,

  ⑷result = [],

  ⑸len = arr.length;

  ⑹arr.forEach(function(v, i ,arr){ //这里利用map,filter方法也可以实现

  ⑺var bool = arr.indexOf(v,i+); //从传入参数的下一个索引值开始寻找是否存在重复

  ⑻if(bool === -){

  ⑼result.push(v);

  ⑽return result;

  ⑾var a = [,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,];

  ⑿var b = a.distinct();

  ⒀console.log(b.toString()); //,,,

  ⒁方法三:数组递归去重

  ⒂Array.prototype.distinct = function (){

  ⒃var arr = this,

  ⒄len = arr.length;

  ⒅arr.sort(function(a,b){ //对数组进行排序才能方便比较

  ⒆return a - b;

  ⒇function loop(index){

  ⒈if(index >= ){

  ⒉if(arr[index] === arr[index-]){

  ⒊arr.splice(index,);

  ⒋loop(index - ); //递归loop函数进行去重

  ⒌loop(len-);

  ⒍return arr;

  ⒎var a = [,,,,,,,,,,,,,,,,,,,,,,];

  ⒏var b = a.distinct();

  ⒐console.log(b.toString()); //,,,,,,,

  ⒑方法四:利用对象的属性不能相同的特点进行去重

  ⒒Array.prototype.distinct = function (){

  ⒓var arr = this,

  ⒔obj = {},

  ⒕result = [],

  ⒖len = arr.length;

  ⒗for(i = ; i< arr.length; i++){

  ⒘if(!obj[arr[i]]){ //如果能查找到,证明数组元素重复了

  ⒙obj[arr[i]] = ;

  ⒚result.push(arr[i]);

  ⒛return result;

  ①var a = [,,,,,,,,,,,,,,,,,,,,];

  ②var b = a.distinct();

  ③console.log(b.toString()); //,,,,,,

  ④方法五:利用splice直接在原数组进行操作

  ⑤Array.prototype.distinct = function (){

  ⑥var arr = this,

  ⑦len = arr.length;

  ⑧for(i = ; i < len; i++){

  ⑨for(j = i + ; j < len; j++){

  ⑩if(arr[i] == arr[j]){

  Ⅰarr.splice(j,);

  Ⅱreturn arr;

  Ⅲvar a = [,,,,,,,,,,,,,,,,,,,,];

  Ⅳvar b = a.distinct();

  Ⅴconsole.log(b.toString()); //,,,,,,

您可能感兴趣的文章:

相关文章