JS 判断数组类型,数组去重,去除重复对象,扁平化等常用方法

163 阅读1分钟

判断是否为数组

判断数组类型的方法:

var arr=[1,2,3];

1.检测类的instanceof

console.log(arr instanceof Array) ;true为数组

2.判断数组的__proto__属性和Array的prototype是否相等

console.log(Array.prototype==arr.proto);//true为数组

3.判断构造函数constructor

console.log(arr.constructor===Array);//true为数组

  1. 数组原生方法 isArray()

    Array.isArray(arr); //true为数组

数组去重

let arr = [1,1,'true','true',true,true,false,false, undefined,undefined, null,null, NaN, NaN,'NaN','NaN', 0, 0, 'a', 'a',{},{}];

1. ES6 Set 去重
  Array.from(new Set(arr)) 
  或
  [...new Set(arr)]
2. 循环 + indexOf
   let newArr = []
   for(let i = 0; i < arr.length; i++) {
       if(newArr.indexOf(arr[i]) < 0) {
           newArr.push(arr[i])
       } 
   }
3. 双重循环for比对
   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--;
           }
       }
   }
4.includes + 循环方式  //IE可能不支持includes语法
   let newArr = []
   for(let i = 0; i < arr.length; i++) {
       if(!newArr.includes(arr[i])) {
           newArr.push(arr[i])
       } 
   }
5.对象键值对去重   //速度最快,但内容占用大
   var temp = {}, newArr = [], val, type;
   for (let i = 0; i < arr.length; i++) {
       val = arr[i];
       type = typeof val;
       if (!temp[val]) {
           temp[val] = [type];
           newArr.push(val);
       } else if (temp[val].indexOf(type) < 0) {
           temp[val].push(type);
           newArr.push(val);
       }
   }
 6. sort去重
   let sortArr = arr.sort(),newArr = [];
   for(let i = 1; i < sortArr.length; i++) {
       if(sortArr[i] !== sortArr[i-1]) {
           newArr.push(arr[i])
       }
   }
 7. 数组递归去重
   let len = arr.length;
    arr.sort(function(a,b){  //对数组进行排序才能方便比较
     return a - b;
    })
    function loop(index){
     if(index >= 1){
      if(arr[index] === arr[index-1]){
       arr.splice(index,1);
      }
      loop(index - 1); //递归loop函数进行去重
     }
    }
    loop(len-1);

数组去重重复对象

1. reduce对比相同键值
    var obj = {};
    var arr = [{
        "id": 11,
        "text": "文本"
    }, {
        "id": 11,
        "text": "文本"
    }, {
        "id": 22,
        "text": "文本"
    }, {
        "id": 22,
        "text": "文本"
    }];

    arr = arr.reduce(function(item, next) {
        obj[next.id] ? '' : obj[next.id] = true && item.push(next);
        return item;
    }, []);
    console.log(arr);
2.判断是否存在相同key
    var result = [];
    var obj = {};
    for(var i =0; i<arr.length; i++){
        if(!obj[arr[i].key]){
            result.push(arr[i]);
            obj[arr[i].key] = true;
        }
    }
    console.log(result); 
   或
   //删除arr中的重复对象
   var newArr= [];
   var arrId = [];
   for(var item of arr){
        if(arrId.indexOf(item['id']) == -1){
            arrId.push(item['id']);
            newArr.push(item);
        }
   }
3.去除完全相同的对象
  function deteleObject(obj) {
    var uniques=[];
    var stringify = {};
    for(var i=0; i<obj.length; i++) {
        var keys = Object.keys(obj[i]);
        keys.sort(function(a, b) {
            return (Number(a) - Number(b));
        });
        var str='';
        for(var j=0; j < keys.length; j ++) {
            str += JSON.stringify(keys[j]);
            str += JSON.stringify(obj[i][keys[j]]);
        }
        if(!stringify.hasOwnProperty(str)) {
            uniques.push(obj[i]);
            stringify[str]=true;
        }
    }
    return uniques.length;
  }
  deteleObject(arr);

数组扁平化

数组的扁平化,就是将多维数组转换为一维数组。
var arr = [1, [2, [3, 4]]];
1. 递归 + 判断数组类型
function flatten(arr){
    var res = [];
    for(var i=0;i<arr.length;i++){
        if(Array.isArray(arr[i])){
            res = res.concat(flatten(arr[i]));
        }else{
            res.push(arr[i]);
        }
    }
    return res;
}
或 reduce方式
function flatten(arr){
    return arr.reduce(function(prev,item){
        return prev.concat(Array.isArray(item)?flatten(item):item);
    },[]);
}
2. toString方式  //全数字
arr.toString() // "1,2,3,4"
3. ...扩展运算符
function flatten(arr){
    while(arr.some(item=>Array.isArray(item)){
        arr = [].concat(...arr);
    }
    return arr;
}
4. 正则处理
arr = str.replace(/(\[\]))/g, '').split(',');
5. flat方法
var newArray = arr.flat(depth) //depth 可选 指定要提取嵌套数组的结构深度,默认值为 1。

获取数组对象索引

let  userList = [
	{
		name: 'liu',
		age: 18
	},
	{
		name: 'li',
		age: 15
	},
	{
		name: 'zhao',
		age: 14
	}
];
let name = 'liu';
let index = this.userList.findIndex(item => item.name === name);
console.log(index)   // 打印出来的结果是 : 0var currentProfile = {
		name: 'liu',
		age: 18
	};
let currentProfileIndex = (userList|| []).findIndex((profile) => profile.name === currentProfile .name);
console.log(currentProfileIndex );