LoginSignup
2
0

More than 3 years have passed since last update.

javascriptで配列から重複していないデータを削除する

Last updated at Posted at 2019-11-02

checkioをやってみて、業務ではあんまりないだろうけど考えさせられる問題だったので解いてみました。

問題内容

const data = [10, 9, 10, 10, 9, 8]
// アウトプットは以下のようにしたい。
// [ 10, 9, 10, 10, 9 ]

上記だと9と10が配列内に重複したデータが存在していますが、8のみ単一のデータとなっています。
こういったインプットに対して、8(重複していないデータ)のみ削除して返すという問題でした。

code

考えた結果が以下のようになります。
他に良い方法があればどなたかご教示ください!

function nonUniqueElements(data) {
    // 重複しているデータだけ抽出
    const duplicatedList = data.filter(function(row, index, self) {
      return self.indexOf(row) !== index
    });

    // 差集合で重複していないデータのリストを生成
    const x = new Set(data)
    const y = new Set(duplicatedList)
    const noDuplicatedList = Array.from(new Set([...x].filter(e => !y.has(e))))

    // 削除処理
    noDuplicatedList.forEach(e => {
      const index = data.indexOf(e)
      if (index === -1) {
        return
      }
      data.splice(index, 1)
    })
    return data
}
2
0
2

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
2
0