如何对 JavaScript 中的二维数组去重?转换为一维数组:使用 Array.prototype.flat() 或 Array.prototype.reduce() 转换为一维数组。去除重复项:使用 Array.prototype.filter() 方法去除重复项。转换为二维数组:使用 Array.prototype.map() 或 Array.prototype.reduce() 转换为二维数组。
如何在 JavaScript 中对二维数组去重
要对 JavaScript 中的二维数组进行去重,可以使用以下步骤:
1. 转换为一维数组
将二维数组转换为一维数组,方法是使用 Array.prototype.flat() 或 Array.prototype.reduce() 方法:
const flattenedArray = array.flat();
或者:
const flattenedArray = array.reduce((acc, val) => acc.concat(val), []);
2. 去除重复项
使用 Array.prototype.filter() 方法去除重复项,方法如下:
const uniqueArray = flattenedArray.filter((item, index) => flattenedArray.indexOf(item) === index);
3. 转换为二维数组
将去重后的一维数组转换为二维数组,方法是使用 Array.prototype.map() 或 Array.prototype.reduce() 方法:
const newArray = []; const rows = 2; const cols = array.length / rows; for (let i = 0; i < rows; i++) { newArray.push(uniqueArray.slice(i * cols, i * cols + cols)); }
或者:
const newArray = uniqueArray.reduce((acc, val, index) => { if (index % cols === 0) acc.push([]); acc[acc.length - 1].push(val); return acc; }, []);
这样就可以得到去重后的二维数组。
以上就是js如何对二维数组去重的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号