关于javascript:数组并集交集差集

2次阅读

共计 3593 个字符,预计需要花费 9 分钟才能阅读完成。

underscore

官网

_.union([2,1,2]); // [2,1]

lodash

官网

_.uniq([2,1,2]); [2,1]

不产生新数组

应用 indexOf 判断和 splice 删除。

const removeDuplicates = (nums) => {
    let len = nums.length - 1
    for(let i = len; i>=0; i--) {if(nums.indexOf(nums[i]) != i) {nums[i] = nums[len --]
        }
    }
    // 删除反复项
    nums.splice(len+1)
    return nums
}
// 测试
removeDuplicates([1, 2, 3, 1, 3])
// [1, 2, 3]

reduce

function unique (arr) {return arr.sort().reduce((acc, cur) => {if (acc.length === 0 || acc[acc.length - 1] !== cur) {acc.push(cur);
     }
     return acc
 }, [])}
;

// 测试
var arr = [1, 2, 2, 3]
unique(arr); // [1, 2, 3]

filter

function unique(arr) {return arr.filter( (element, index, array) => {return array.indexOf(element) === index
 })
}

// 测试
var arr = [1, 2, 2, 3]
unique(arr); // [1, 2, 3]

ES5

ES5 能够利用 filterindexOf 和进行数学集操作,然而,因为 indexOf 办法中 NaN 永远返回 -1,所以须要进行兼容解决。

var a = [1,2,3];
var b = [1,2,2,4];

// 并集(去重)var union = a.concat(b.filter(function(v) {return a.indexOf(v) === -1 } )); // [1,2,3,4]
// 交加
var intersection = a.filter(function(v){return b.indexOf(v) > -1 }); // [1,2]
// 差集
var difference = a.filter(function(v){return b.indexOf(v) === -1 }); // [3]

ES6

ES6 中新增的一个 Array.from 办法,用于将类数组对象和可遍历对象转化为数组。只有类数组有 length 长度,根本都能够转化为数组。联合 Set 构造实现数学集求解。

let a = [1,2,3];
let b = [1,2,2,4];

let aSet = new Set(a);
let bSet = new Set(b);

// 并集(去重)let union = Array.from(new Set(a.concat(b))); // [1,2,3,4]
// 交加
let intersection = Array.from(new Set(a.filter(v => bSet.has(v)))); // [2]
// 差集
let differenceNew = Array.from(new Set(a.concat(b).filter(v => aSet.has(v) && !bSet.has(v))); // [3]

ES7

ES7 新增了一个 Array.prototype.includes 的数组办法,用于返回一个数组是否蕴含指定元素,联合 filter 办法。

let a = [1,2,3];
let b = [1,2,2,4];

// 并集(去重)let union = a.concat(b.filter(v => !a.includes(v))); // [1,2,3,4]
// 交加
let intersection = a.filter(v => b.includes(v)); // [1,2]
// 差集
let difference = a.concat(b).filter(v => a.includes(v) && !b.includes(v)); // [3]

数组扁平化(数组降维)

MDNflat()办法会依照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

const test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]

// flat 不传参数时,默认扁平化一层
test.flat()
// ["a", "b", "c", "d", ["e", ["f"]], "g"]

// flat 传入一个整数参数,整数即扁平化的层数
test.flat(2)
// ["a", "b", "c", "d", "e", ["f"], "g"]

// Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组
test.flat(Infinity)
// ["a", "b", "c", "d", "e", "f", "g"]

// 传入 <=0 的整数将返回原数组,不扁平化
test.flat(0)
test.flat(-1)
// ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]

// 如果原数组有空位,flat()办法会跳过空位。["a", "b", "c", "d",,].flat()
// ["a", "b", "c", "d"]

Array.prototype.flat()

  • Array.prototype.flat() 用于将嵌套的数组扁平化,成为一维数组。该办法返回一个新的数组,对原数据没有影响
  • 不传参数时,默认扁平化一层;传入一个整数时,这个整数代码想要扁平化的层数
  • 传入 <=0 的整数将不进行扁平化,返回原数组
  • Infinity 关键字作为参数时,无论是多少层嵌套,都会转为一维数组
  • 另外,留神:如果原数组有空位,Array.prototype.flat() 会跳过空位

手写扁平化函数

一、应用 reduce 办法

function flattenDeep(arr) {return Array.isArray(arr)
      ? arr.reduce((acc, cur) => [...acc, ...flattenDeep(cur)] , [])
      : [arr]
}

// 测试
var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
flattenDeep(test)
// ["a", "b", "c", "d", "e", "f", "g"]

实现 flat 函数:

function flat(arr, depth = 1) {
    return depth > 0
        ? arr.reduce((acc, cur) => {if(Array.isArray(cur)) {return [...acc, ...flat(cur, depth-1)]
        }
        return [...acc, cur]
    } , [])
      : arr
}

// 测试
var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
// 不传参数时,默认扁平化一层
flat(test)
// ["a", "b", "c", "d", ["e", ["f"]], "g"]

// 传入一个整数参数,整数即扁平化的层数
flat(test, 2)
// ["a", "b", "c", "d", "e", ["f"], "g"]

// Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组
flat(test, Infinity)
// ["a", "b", "c", "d", "e", "f", "g"]

// 传入 <=0 的整数将返回原数组,不扁平化
flat(test, 0)
flat(test, -10)
// ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]];

// 如果原数组有空位,flat()办法会跳过空位。var arr = ["a", "b", "c", "d",,]
flat(arr)
// ["a", "b", "c", "d"]

二、栈

function flattenDeep(arr) {const result = [] 
  // 将数组元素拷贝至栈,间接赋值会扭转原数组
  const stack = [...arr]
  // 如果栈不为空,则循环遍历
  while (stack.length !== 0) {const val = stack.pop() 
    if (Array.isArray(val)) {
      // 如果是数组再次入栈,并且开展了一层
      stack.push(...val) 
    } else {
      // 如果不是数组,就用头插法插入到后果数组中
      result.unshift(val)
    }
  }
  return result
}

// 测试
var test = ["a", ["b", "c"], ["d", ["e", ["f"]], "g"]]
flattenDeep(animals)
// ["a", "b", "c", "d", "e", "f", "g"]

参考起源:

https://mp.weixin.qq.com/s/VRjEtRYj6mvp2-YW4iKMdQ

https://mp.weixin.qq.com/s/NGl9nBkIruuzYkxqyPnB1A

正文完
 0