JavaScript数组中筛选相同的元素组成新数组

2023-11-08

var college = [
	{type:2,lastName:'孙策'},
	{type:1,lastName:'后裔'},
	{type:3,lastName:'阿木木'},
	{type:3,lastName:'亚索'},
	{type:1,lastName:'剑魔'},
	{type:1,lastName:'拉克丝'},
	{type:2,lastName:'盖伦'},
	{type:2,lastName:'石头人'},
	{type:1,lastName:'莫甘娜'}
];

//先用map结构记录
function arrayToMap(data) {
  //非数组或数据长度为0不处理
  if(!data instanceof Array || data.length == 0) {
    return {};
  }
  var map = {};
  for(var i=0;i<data.length;i++) {
    if(!data[i] instanceof Array || data.length < 2) {
      continue;
    }

    let name = data[i].type;
    if(name != undefined) {
      if(map[name] == undefined) {
        map[name] = [];
      }
      map[name].push(data[i]);
    }
  }
  return map;
}

//把map转成数组
function mapToArray(data) {
  if(data == undefined) {
    return [];
  }
  let array = [];
  for(let p in data) {
    array.push(data[p]);
  }
  return array;
}

//测试
var map = arrayToMap(college);
var array = mapToArray(map);
console.log('筛选后对象',map)
console.log('筛选后数组',array)

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript数组中筛选相同的元素组成新数组 的相关文章