返回
JS数组操作:去重、交集、并集、差集
前端
2023-11-13 19:59:42
引言
JavaScript数组是一个非常强大的数据结构,它可以存储各种类型的数据,包括数字、字符串、布尔值、对象和数组。数组中的元素可以重复,也可以是唯一的。
在JavaScript中,有很多方法可以对数组进行操作,其中最常用的四种操作是去重、交集、并集和差集。
数组去重
数组去重操作可以去除数组中重复的元素,只保留唯一的元素。
实现数组去重的最简单方法是使用Set对象。Set对象是一个无序集合,它只存储唯一的元素。我们可以将数组中的元素添加到Set对象中,然后将Set对象转换为数组,这样就可以得到一个去重后的数组。
const array = [1, 2, 3, 4, 5, 1, 2, 3];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
数组交集
数组交集操作可以求出两个数组中都存在的元素。
实现数组交集的最简单方法是使用filter()方法。我们可以使用filter()方法来过滤两个数组中的元素,只保留那些在两个数组中都存在的元素。
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const intersection = array1.filter((element) => array2.includes(element));
console.log(intersection); // [3, 4, 5]
数组并集
数组并集操作可以求出两个数组中所有元素的集合。
实现数组并集的最简单方法是使用concat()方法。我们可以使用concat()方法来连接两个数组,这样就可以得到一个并集数组。
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const union = array1.concat(array2);
console.log(union); // [1, 2, 3, 4, 5, 3, 4, 5, 6, 7]
数组差集
数组差集操作可以求出两个数组中不相同的元素。
实现数组差集的最简单方法是使用filter()方法。我们可以使用filter()方法来过滤两个数组中的元素,只保留那些在第一个数组中存在、但在第二个数组中不存在的元素。
const array1 = [1, 2, 3, 4, 5];
const array2 = [3, 4, 5, 6, 7];
const difference = array1.filter((element) => !array2.includes(element));
console.log(difference); // [1, 2]
结语
JS数组的去重、交集、并集和差集操作非常有用,可以帮助您处理和分析数组数据。这些操作的实现也很简单,可以使用JavaScript的内置方法来实现。