如何获得数组中的不同元素?

时间:2018-10-23 10:54:24

标签: javascript

让我们看一下我们有一个数组,该数组的元素的数目,类型和值未知。例如,我们有一个数组,预期结果是它包含200个“ a”元素,300个“ b”元素和500个“ c”元素。但是同样,我们不知道元素的值,数量,位置。使它们像上面的结果一样最简单的方法是什么?

1 个答案:

答案 0 :(得分:0)

请以最简单的方式使用简单的while循环删除重复项,并找到数组的唯一元素。

let alphaNumeric = ["a","a","a","a","a","a","a","a","a","a","b","b","b","b","b","b","b","b","c","c","c","c","c","c","c","c","1","1","1","1","1","a", "d","#","!", "p", "d", "d", "d", "d", "d"];
let i = 0;
let length = alphaNumeric.length;
let removeDuplicate = []; 
while(i < length) {
  if (!removeDuplicate.includes(alphaNumeric[i])){
    removeDuplicate.push(alphaNumeric[i]);
  }
  i += 1;
}
console.log(removeDuplicate);

希望,它会有所帮助。