Lodash _.Intersection() 方法
Lodash 是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、字符串、对象、数字等。
_.intersection()方法用于获取一个或多个数组的交集。与集合论中的交集相同。
句法:
_.intersection([arrays])
参数:它需要一个数组作为参数。
返回值:返回数组相交后的数组。
注意:在使用下面给出的代码之前,请使用命令npm install lodash
安装 lodash 模块。
示例 1:取两个数组的交集。
Javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
let array1 = [1, 2, 4, 3, 4, 4]
let array2 = [2, 4, 5, 6]
// Using _.intersection() method
let newArray = lodash.intersection(
array1, array2);
// Printing original Array
console.log("original Array1: ", array1)
console.log("original Array2: ", array2)
// Printing the newArray
console.log("new Array: ", newArray)
Javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
let array1 = [1, 2, 4, 3, 4, 4]
let array2 = [2, 4, 5, 6]
let array3 = [2, 3, 5, 6]
// Using _.intersection() method
let newArray = _.intersection(
array1, array2, array3);
// Printing original Array
console.log("original Array1: ", array1)
console.log("original Array2: ", array2)
console.log("original Array3: ", array3)
// Printing the newArray
console.log("new Array: ", newArray)
Javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
let array1 = [1, 2, 4, 3, 4, 4]
let array2 = []
// Using _.intersection() method
let newArray = lodash
.intersection(array1, array2);
// Printing original Array
console.log("original Array1: ", array1)
console.log("original Array2: ", array2)
// Printing the newArray
console.log("new Array: ", newArray)
输出:
示例 2:取两个以上数组的交集。
Javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
let array1 = [1, 2, 4, 3, 4, 4]
let array2 = [2, 4, 5, 6]
let array3 = [2, 3, 5, 6]
// Using _.intersection() method
let newArray = _.intersection(
array1, array2, array3);
// Printing original Array
console.log("original Array1: ", array1)
console.log("original Array2: ", array2)
console.log("original Array3: ", array3)
// Printing the newArray
console.log("new Array: ", newArray)
输出:
示例 3:数组与空数组的交集。
Javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
let array1 = [1, 2, 4, 3, 4, 4]
let array2 = []
// Using _.intersection() method
let newArray = lodash
.intersection(array1, array2);
// Printing original Array
console.log("original Array1: ", array1)
console.log("original Array2: ", array2)
// Printing the newArray
console.log("new Array: ", newArray)
输出: