1、数组去重
//去重
function noReapt(arr){
let result = [];
arr.forEach((item) => {
if(result.indexOf(item) == -1){
result.push(item);
}
});
return result;
//或直接return Array.from(new Set(arr));
}
console.log(noReapt([2,2,1,5,3,8,1])); // [2, 1, 5, 3, 8]
2、随机排序
//随机排序
function randomSort(arr){
arr.sort(() => {
return Math.random() - 0.5;
});
return arr;
}
console.log(randomSort([2,2,1,5,3,8,1])); //[5, 2, 3, 2, 1, 1, 8]
3、N维数组变一维数组
方法一:
var arr = [1,2,3,[3,4,[2,1,['sd']]]];
function handle(arr){
var result = [];
for(var key in arr){
if(arr[key] instanceof Array){
result = result.concat(handle(arr[key]));
}else{
result.push(arr[key]);
}
}
return result;
}
console.log(handle(arr)); //[1, 2, 3, 3, 4, 2, 1, "sd"]
方法二:用ES6的flat()
var arr = [1,2,3,[3,4,[2,1,['sd']]]];
console.log(arr.flat(Infinity)); //[1, 2, 3, 3, 4, 2, 1, "sd"]
4、交集
//求两数组的交集
function arrPublic(arr1,arr2){
let result = [];
for(let i = 0; i < arr1.length; i++){
if(result.indexOf(arr1[i]) >= 0){
continue;
}else if(arr2.indexOf(arr1[i]) >= 0){
result.push(arr1[i]);
}
}
return result;
}
console.log(arrPublic([1,2,5,3,2],[1,3,3,8])); //[1, 3]
5、并集
//求两数组的并集
function arrSum(arr1,arr2){
let result = [].concat(arr1,arr2);
return noReapt(result); //调用上面的去重函数
}
console.log(arrSum([1,2,5,3,2],[1,3,3,8]));//[1, 2, 5, 3, 8]
6、差集
///求两个数组的差集 ,结果顺便去个重
//eg:{1,2,3} - {2,4} = {1,3}
function chaji(arr1,arr2){
let result = [];
arr1.forEach((item) => {
if(arr2.indexOf(item) == -1 && result.indexOf(item) == -1){
result.push(item);
}
});
return result;
}
console.log(chaji([1,1,2,3],[2,4]));//[1, 3]
#练习:
(1)移除数组arr中的所有与 item 相等的元素,必须在原数组上做修改
//移除数组arr中的所有与 item 相等的元素
//要求:必须在原数组上做修改
function removeWithoutCopy(arr,item) {
var index = 0;
while((index = arr.indexOf(item)) != -1){
arr.splice(index,1);
}
return arr;
}
console.log(removeWithoutCopy([1,2,2,3,4,2,2],2));//[1, 3, 4]