字符串数组去重 ["a","b","c","a","b","c"] --> ["a","b","c"]

非正则实现: 

let str_arr=["a","b","c","a","b","c"]

function unique(arr){
  return [...new Set(arr)]
}

console.log(unique(str_arr)) // ["a","b","c"]

用正则实现:

var str_arr = ["a", "b", "c", "a", "b", "c"]

function unique(arr) {
    return arr.sort().join(",,").
    replace(/(,|^)([^,]+)(,,\2)+(,|$)/g, "$1$2$4").
    replace(/,,+/g, ",").
    replace(/,$/, "").
    split(",")
}

console.log(unique(str_arr)) // ["a","b","c"]

posted @ 2017-08-23 17:02  Martin_lee  阅读(316)  评论(0编辑  收藏  举报