js的数组去重的几种方式
// 1.es6新特性--
var arr1 = [1, 2, 2, 3, 3, 2, 4, 1, 5, 7, 9, 7, 5, 8, 6];
function unique(arr) {
return [...new Set(arr1)];
}
console.log(unique(arr1));
// 2. indexOf去重
var arr2 = [1, 2, 2, 3, 3, 2, 4, 1, 5, 7, 9, 7, 5, 8, 6];
function uniqueIndexOf(arr) {
var arrIndexOf = [];
for (let i = 0; i < arr.length; i++) {
if (arrIndexOf.indexOf(arr[i]) == -1) {
arrIndexOf.push(arr[i]);
}
}
return arrIndexOf;
}
console.log(uniqueIndexOf(arr2));
// 3. 排序的方式
var arr3 = [1, 2, 2, 3, 3, 2, 4, 1, 5, 7, 9, 7, 5, 8, 6];
function uniqueSort(arr) {
arr = arr.sort();
var arrSort = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
arrSort.push(arr[i])
}
}
return arrSort;
}
console.log(uniqueSort(arr3));
// 4. for循环
var arr4 = [1, 2, 2, 3, 3, 2, 4, 1, 5, 7, 9, 7, 5, 8, 6];
function uniqueFor(arr) {
var arrFor = []
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
arr.splice(j, 1);
j--;
}
}
}
return arr;
}
console.log(uniqueFor(arr4));
// 5.filter
var arr5 = [1, 2, 2, 3, 3, 2, 4, 1, 5, 7, 9, 7, 5, 8, 6];
function uniqueFilter(arr) {
// self 指的是自己本身数组
return arr.filter((item, index, self) => {
return self.indexOf(item, 0) === index;
})
}
console.log(uniqueFilter(arr5));
java中的去重比较简单
// 普通list
public Object[] Unique(Object[] arr) {
List<Object> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (!list.contains(arr[i])) {
list.add(arr[i]);
}
}
Object[] objects = list.toArray();
return objects;
}
// HashSet
public Object[] UniqueSet(Object[] arr) {
Set set = new HashSet();
for (int i = 0; i < arr.length; i++) {
set.add(arr[i]);
}
return set.toArray();
}
// LinkedHashSet 去重
public Object[] UniqueLinkHash(Object[] arr) {
Set set = new LinkedHashSet();
for (int i = 0; i < arr.length; i++) {
set.add(arr[i]);
}
return set.toArray();
}