1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

js 二つの文字列を一つにする

Last updated at Posted at 2017-01-10

##お題
与えられる二つの引数(アルファベット文字列)を以下の条件を満たしつつ一つに結合する。
・アルファベットを順番に並べかえる
・重なった文字は省略する

function longest(s1, s2) {
 //write your code.
}
longest("xyaabbbccccdefww", "xxxxyyyyabklmopq") // "abcdefklmopqwxy"

##出力結果 例

longest("aretheyhere", "yestheyarehere")// "aehrsty"
longest("loopingisfunbutdangerous", "lessdangerousthancoding")// "abcdefghilnoprstu"
longest("inmanylanguages", "theresapairoffunctions")// "acefghilmnoprstuy"

##つかったもの
split()
sort()
filter()
join()

##考え方
・引数を合わせてから文字ごとに分割する。
・sort()で並べ替えて、filterで重複したものを省く。
(filterの条件を工夫する)
・join()でfilter後の文字を一緒にして返しておわり。

##コード

function longest(s1, s2) {
  s3 = s1 + s2;
  s4 = s3.split("");
  s4 = s4.sort().filter(function(element, index, array){
    return element !== array[index - 1];
  });
  return s4.join("");
}

ES6

function longest(s1, s2) {
  return Array.from(new Set(s1 + s2)).sort().join('');
}
const longest = (s1, s2) => [...new Set(s1+s2)].sort().join('');

###他にもコードが浮かんだ方、コメントお待ちしております

1
4
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?