在JavaScript中,操作两个数组并返回一个新数组的方式有很多。以下是几种常见的方法,涵盖了不同类型的操作,如合并、过滤、映射、交集、并集、差集等:
1. 合并两个数组(Concatenation)
使用concat方法或展开运算符...来合并两个数组。
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
// 方法1: 使用 concat
let mergedArray = array1.concat(array2);
// 方法2: 使用展开运算符
let mergedArray2 = [...array1, ...array2];
console.log(mergedArray); // [1, 2, 3, 4, 5, 6]
2. 数组的交集(Intersection)
返回两个数组中都包含的元素。可以使用filter结合includes来实现。
let array1 = [1, 2, 3];
let array2 = [2, 3, 4];
let intersection = array1.filter(value => array2.includes(value));
console.log(intersection); // [2, 3]
3. 数组的并集(Union)
返回两个数组的并集,可以使用concat和Set来去重。
let array1 = [1, 2, 3];
let array2 = [2, 3, 4];
let union = [...new Set([...array1, ...array2])];
console.log(union); // [1, 2, 3, 4]
4. 数组的差集(Difference)
返回存在于第一个数组而不在第二个数组中的元素。
let array1 = [1, 2, 3];
let array2 = [2, 3, 4];
let difference = array1.filter(value => !array2.includes(value));
console.log(difference); // [1]
5. 数组的对称差集(Symmetric Difference)
返回两个数组中独有的元素,即并集减去交集。
let array1 = [1, 2, 3];
let array2 = [2, 3, 4];
let symmetricDifference = array1
.filter(value => !array2.includes(value))
.concat(array2.filter(value => !array1.includes(value)));
console.log(symmetricDifference); // [1, 4]
6. 数组的映射(Mapping)
结合两个数组的元素生成一个新数组,可以使用map。
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let mappedArray = array1.map((value, index) => value + array2[index]);
console.log(mappedArray); // [5, 7, 9]
7. 交替合并(Zipping)
将两个数组中的对应元素合并为一个二维数组,类似于"拉链"效果。
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let zippedArray = array1.map((value, index) => [value, array2[index]]);
console.log(zippedArray); // [[1, 4], [2, 5], [3, 6]]
8. 数组扁平化(Flattening Arrays)
有时你可能会将两个嵌套数组合并并进行扁平化。可以使用flat。
let array1 = [1, 2, [3, 4]];
let array2 = [5, [6, 7]];
let flattenedArray = [...array1, ...array2].flat();
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6, 7]
这些方法能够帮助你在JavaScript中对两个数组进行各种常见的操作,并返回一个新数组。根据具体需求选择合适的方法即可。