从 JavaScript 中的数组中获取唯一的项
我们需要创建一个函数,它接受一个数组数组,并返回一个新数组,其中包含原始数组数组中存在的所有元素,但删除了重复项。
例如 - 如果输入是 -
const arr = [ [12, 45, 65, 76, 76, 87, 98], [54, 65, 98, 23, 78, 9, 1, 3], [87, 98, 3, 2, 123, 877, 22, 5, 23, 67] ];
则输出应该是这样的唯一元素的单个数组 -
[ 12, 45, 54, 78, 9, 1, 2, 123, 877, 22, 5, 67 ]
示例
const arr = [
[12, 45, 65, 76, 76, 87, 98],
[54, 65, 98, 23, 78, 9, 1, 3],
[87, 98, 3, 2, 123, 877, 22, 5, 23, 67]
];
const getUnique = (arr) => {
const newArray = [];
arr.forEach((el) => newArray.push(...el));
return newArray.filter((item, index) => {
return newArray.indexOf(item) === newArray.lastIndexOf(item);
});
};
console.log(getUnique(arr));输出
控制台中的输出将是 -
[ 12, 45, 54, 78, 9, 1, 2, 123, 877, 22, 5, 67 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP