Skip to content

js 常用的一些算法

判断一个二维数组中的所有子数组,是否全部相同(不关心子数组的顺序)

  • 示例:[[3, 1, 2],[2, 3, 1],[1, 2, 3]];
  • 结果:相同,返回这个相同的子数组,否则返回空数组
js
// 判断数组中子数组是否全部相同
function childArrIsSame (value) {
  const arr = value.map((item) => item.sort())
  const first = JSON.stringify(arr[0])
  return arr.every((item) => JSON.stringify(item) === first) ? arr[0] : []
}

判断数组中是否出现重复元素

  • 示例:['a', 'b', 'c', 'd', 'a'];
  • 结果:有重复,返回true,否则返回false
js
// 判断数组中是否出现重复元素
function  hasDuplicates(array) {
  const seen = {};
  for (const element of array) {
    if (seen[element]) {
      console.log("hasDuplicates", element)
      return true;
    }
    seen[element] = true;
  }
  console.log("noDuplicates")
  return false;
}