// 示例代码:js 二维数组去重
function unique2DArray(arr) {
// 创建一个 Map 来存储子数组及其出现的次数
const map = new Map();
// 遍历二维数组,将每个子数组转换为字符串作为键存入 Map
for (let i = 0; i < arr.length; i++) {
const key = JSON.stringify(arr[i]);
if (!map.has(key)) {
map.set(key, true);
}
}
// 将 Map 中的键(子数组)转换回二维数组
return Array.from(map.keys()).map(JSON.parse);
}
// 示例用法
const array = [[1, 2], [3, 4], [1, 2], [5, 6], [3, 4]];
const result = unique2DArray(array);
console.log(result); // 输出: [ [1, 2], [3, 4], [5, 6] ]
Map
来存储子数组。由于 Map
的键是唯一的,因此可以确保不会重复。JSON.stringify
将每个子数组转换为字符串形式,以便作为 Map
的键。Map
中,则将其添加到 Map
。Map
中的所有键(子数组的字符串形式)转换回原始的二维数组形式。这样就实现了二维数组的去重。
上一篇:js 截取字符串
下一篇:js 二维数组排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站