有一个数组 arr=["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"];
我想获取这组数据有不同的水果类型,有3类,如何获取这个3了?
//支持es6
let arr=["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"];
let arrNew = Array.from(new Set(arr))
console.log(arrNew)
看我文章有封装 可调用
“ https://segmentfault.com/a/11...
//不支持es6 简单去重
百度一堆 就不写了
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;
}
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"]
var arr=["苹果","苹果","西瓜","苹果","西瓜","香蕉","香蕉"];
console.log(Array.from(new Set(arr)));
(没看见 原来楼上已经有写的了)
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);
8 回答4.7k 阅读✓ 已解决
6 回答3.4k 阅读✓ 已解决
5 回答2.8k 阅读✓ 已解决
5 回答6.3k 阅读✓ 已解决
4 回答2.3k 阅读✓ 已解决
4 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
= = 对不起 我傻逼了 谢谢楼上提醒