LoginSignup
1
1

More than 3 years have passed since last update.

JS 配列内で重複しているものは削除して返す

Last updated at Posted at 2020-07-16

Lodashのuniq関数を作ってみた

includeメゾッドの場合

const uniq = (array) => {
  const uniqArray = []
  for (let i = 0; i < array.length; i++) {
    const setArray = array[i]
    if (!uniqArray.includes(setArray)) {
      uniqArray.push(setArray)
    }
  }
  return uniqArray
}
console.log(uniq([2, 1, 2, 4, 8, 5, 4, 8]))

setメゾッドの場合

const uniq = (array = []) => {
  const uniqArray = [...new Set(array)]
  return uniqArray
}
console.log(uniq([2, 1, 2, 4, 8, 5, 4, 8]))

[7月20日更新]
@standard-software さんからご指摘頂き、Set部分の誤った記述を修正しました。
とても助かります、ありがとうございました!!

1
1
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
1
1