Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

根据以下要求,写一个数组去重函数(蘑菇街) #8

Open
lovelmh13 opened this issue Jan 30, 2020 · 0 comments
Open

根据以下要求,写一个数组去重函数(蘑菇街) #8

lovelmh13 opened this issue Jan 30, 2020 · 0 comments

Comments

@lovelmh13
Copy link
Owner

lovelmh13 commented Jan 30, 2020

如传入的数组元素为[123, "meili", "123", "mogu", 123],则输出:[123, "meili", "123", "mogu"]

如传入的数组元素为[123, [1, 2, 3], [1, "2", 3], [1, 2, 3], "meili"],则输出:[123, [1, 2, 3], [1, "2", 3], "meili"]

如传入的数组元素为[123, {a: 1}, {a: {b: 1}}, {a: "1"}, {a: {b: 1}}, "meili"],则输出:[123, {a: 1}, {a: {b: 1}}, {a: "1"}, "meili"]

自己写的比较麻烦,性能也不是很好

var arr1 = [123, 'meili', '123', 'mogu', 123]
var arr2 = [123, [1, 2, 3], [1, '2', 3], [1, 2, 3], 'meili']
var arr3 = [
  123,
  { a: 1 },
  { a: { b: 1 } },
  { a: '1' },
  { a: { b: 1 } },
  'meili'
]
var arr4 = [
  123,
  { a: 1 },
  { a: { b: 1 } },
  { a: '1' },
  { a: { b: 1 } },
  'meili',
  [1, 2, 3],
  [1, '2', 3],
  [1, 2, 3]
]
function unique(arr) {
  var arrSet = [...new Set(arr)]
  var arr = []
  var obj = []
  arrSet.map((item, index) => {
    type(item, index, arr, obj)
  })
  if (arr.length > 0) {
    for (var i = 0; i < arr.length - 1; i++) {
      for (var j = i + 1; j < arr.length; j++) {
        // 通过对应的角标删除arrSet对应的项
        var index1 = arr[i]
        var index2 = arr[j]
        if (
          JSON.stringify(arrSet[index1]) ===
          JSON.stringify(arrSet[index2])
        ) {
          arrSet.splice(index2, 1)
        }
      }
    }
  }
  if (obj.length > 0) {
    for (var i = 0; i < obj.length - 1; i++) {
      for (var j = i + 1; j < obj.length; j++) {
        var index1 = obj[i]
        var index2 = obj[j]
        if (
          JSON.stringify(arrSet[index1]) ===
          JSON.stringify(arrSet[index2])
        ) {
          arrSet.splice(index2, 1)
        }
      }
    }
  }
  return arrSet
}
function type(item, index, arr, obj) {
  if (item instanceof Object) {
    if (Array.isArray(item)) {
      arr.push(index) // 如果是数组,把对应的角标传入arr
    } else {
      obj.push(index) // 如果是对象,把对应的角标传入obj
    }
  }
}
console.log(unique(arr4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant