# js数组去重（包括ES6解决方案）

## 问题

Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters, – each taken only once – coming from s1 or s2.

``````a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"

a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"``````

## My Solution

``````    function longest(s1, s2) {
let distStr,
value,
distArr = []
getDistinct(distArr, s1 + s2)
// 数组排序并转成字符串
distStr = distArr.sort().join('')
return distStr
}
// 数组去重
function getDistinct(target, source) {
let value
// 将字符串转成数组
source = Array.from(source)
for(value of source) {
// 假如target数组中没有该value，则将其增加到数组中
if(!target.includes(value)) {
target.push(value)
}
}
}
``````

## Best Solution

``const longest = (s1, s2) => [...new Set(s1+s2)].sort().join('')``

## Other Solution

``````    function longest(s1, s2) {
var distStr,
value,
distArr = []
getDistinct(distArr, s1 + s2)
// 数组排序并转成字符串
distStr = distArr.sort().join('')
return distStr
}
// 数组去重
function getDistinct(target, source) {
var index,
value
// 将字符串转成数组
source = Array.prototype.slice.call(source, 0)
for(index in source) {
value = source[index]
// 假如target数组中没有该value，则将其增加到数组中
if(target.indexOf(value) === -1) {
target.push(value)
}
}
}
``````

``````    function longest(s1, s2) {
var distStr,
value,
distArr = []
getDistinct(distArr, s1 + s2)
// 数组排序并转成字符串
distStr = distArr.sort().join('')
return distStr
}
// 数组去重
function getDistinct(target, source) {
var hash = {},
index,
value
// 将字符串转成数组
source = Array.prototype.slice.call(source, 0)
for(index in source) {
value = source[index]
// 假如hash对象中没有该key，则将其增加到数组中
if(!hash[value]) {
target.push(value)
// 给hash增加一个value属性，值为true
hash[value] = true
}
}
}
``````

``````    function longest(s1, s2) {
var distStr,
value,
distArr = []
getDistinct(distArr, s1 + s2)
// 数组排序并转成字符串
distStr = distArr.join('')
return distStr
}
// 数组去重
function getDistinct(target, source) {
var index,
value
// 将字符串转成数组
source = Array.prototype.slice.call(source, 0)
source = source.sort()
for(index in source) {
value = source[index]
// 假如target数组中没有该value，则将其增加到数组中
if(value !== source[index + 1]) {
target.push(value)
}
}
}        ``````

## 结语

原文作者：chenBright
原文地址: https://segmentfault.com/a/1190000007055929
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。