问题描述:
开发中在使用多级可选tree树形菜单时,可能会遇到需要将有重复字符串数组去重并转换成字符串的情况,举个例子如下:
原数组:
["5","10","11","5,10","5,10,11"]
目标字符串:
"5,10,11"
解决思路:
1. 将数组转换成字符串;
2. 将字符串转换成数组再排序;
3. 对排序的结果去重;
4. 将去重后的数组转换成字符串
问题解决:
var arr= ["5","10","11","5,10","5,10,11"]
var strs = arr.join(",");
arr = strs.split(",");
arr.sort(); //排序
for(var i=arr.length-1;i>0;i--){
if(arr[i]==arr[i-1]){
arr.splice(i,1); //数组去重
}
}
strs= arr.join(",");