js使用逗号拼接id并去重

var ids = '111,222,333,333,444,111';
// 将字符串转化成数组
var idsArr = ids.split(","); //[111,222,333,333,444,111]
// 数组去重
var uniqueIds = unique(idsArr); //[111,222,333,444]
ids = '';
//数组转成用逗号分隔的字符串
uniqueIds.forEach(function(item) {
    if(ids == '') {
        ids = item;
    } else {
        ids = ids + ',' + item;
    }
}) 
//'111,222,333,444'

//数组去重
 function unique(arr){
      var newArr = [];
      for(var i = 0; i < arr.length; i++){
          for(var j = i+1; j < arr.length; j++){
              if(arr[i] == arr[j]){
                  ++i;
              }
          }
          newArr.push(arr[i]);
      }
      return newArr;
  }

  

posted @ 2021-10-09 11:21  浅绿色i  阅读(768)  评论(0编辑  收藏  举报