JS获取数组里面有不同类型

有一个数组 arr=["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"];
我想获取这组数据有不同的水果类型,有3类,如何获取这个3了?

阅读 6.6k
13 个回答
const fruit = {}
const arr = ["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"]
arr.forEach(item => fruit[item] ? fruit[item]++ : fruit[item] = 1)
console.log(Object.keys(fruit).length)

= = 对不起 我傻逼了 谢谢楼上提醒

console.log(new Set(["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"]).size)

这是个数组去重的问题。
var arrLen = [...new Set(arr)].length;

//支持es6
let arr=["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"];
let arrNew = Array.from(new Set(arr))
console.log(arrNew) 
看我文章有封装 可调用

https://segmentfault.com/a/11...


//不支持es6  简单去重
百度一堆 就不写了

就是一个简单的去重

arr.reduce((p,n)=>{
    if(p.indexOf(n) === -1){
        p.push(n)
    }
    return p;
},[])
      var arr=["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"];
      var fruits ={}
      arr.forEach((value)=>{
        fruits[value] = 1
      })

      var arr1 = []
      for(var fruit in fruits){
        arr1.push(fruit)
      }
      console.log(arr1);
var arr=["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"];

console.log("类型数量:" , typeCount(arr));

// 获取类别数量的函数
function typeCount(typeArr){
    var typeSet   = [];
    
    typeArr.forEach(function(v , k , arr){
        if (typeSet.search(v) === -1) {
            typeSet.push(v);
        }
    });
    
    return typeSet.length;
}

用loadash

_.uniq(你的数组)
function find_duplicate_in_array(arra1) {
  var i,
  len=arra1.length,
  result = [],
  obj = {}; 
  for (i=0; i<len; i++)
  {
  obj[arra1[i]]=0;
  }
  for (i in obj) {
  result.push(i);
  }
  return result;
  }
var arr = [1, 2, -2, 4, 5, 4, 7, 8, 7, 7, 71, 3, 6];
console.log(find_duplicate_in_array(arr));

效果:
["1","2","3","4","5","6","7","8","71","-2"]

参考:JavaScript: Find duplicate values in a array

var arr=["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"];
console.log(Array.from(new Set(arr)));
(没看见 原来楼上已经有写的了)

新建一个数组,对获取的数据进行遍历,没有的push进去,有的排除,然后再输出一下数据的长度,就可以了

var arr = ["苹果", "苹果", "西瓜", "苹果", "西瓜", "香蕉", "香蕉"];
    var map = {};
    var count = 0;
    for (var i = 0; i < arr.length; i++) {
        if (!map[arr[i]]) {
            map[arr[i]] = true;
            count++;
        }
    }
    console.log(count)

利用对象的映射

同楼上,用对象映射比去数组里查下标快多了,ES6的话直接用Set

var arr = ["苹果", "苹果", "西瓜", "苹果", "西瓜", "香蕉", "香蕉"];
var resolveArr = function () {
  var obj = {};
  arr.forEach(function (v) {
    if (!obj[v]) {
      obj[v] = 1;     
    }
  });
  return Object.keys(obj);
};
console.log(resolveArr(arr));
//是不是很弱智,这么长,hhh

var obj = {};
var arr = ["苹果", "苹果", "苹果", "西瓜", "苹果", "西瓜", "香蕉", "香蕉"];
var newArr = [];
var l = arr.length;
for (var i = 0; i < l; i++) {
  var item = arr[i];
  if (!obj[item]) {
    newArr.push(item);
    obj[item] = 1;
  }
}
console.log(newArr);

 var a = ["苹果", "苹果", "西瓜", "苹果", "西瓜", "香蕉", "香蕉"],
n = a.filter(function(e, i, a) {
  return a.indexOf(e) === i;
});
console.log(n);
推荐问题
宣传栏