How to count duplicate value in an array in javascript

前端 未结 28 1800
后悔当初
后悔当初 2020-11-22 06:07

Currently, I got an array like that:

var uniqueCount = Array();

After a few steps, my array looks like that:

uniqueCount =          


        
28条回答
  •  时光取名叫无心
    2020-11-22 06:18

    var uniqueCount = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
    // here we will collect only unique items from the array
    var uniqueChars = [];
    
    // iterate through each item of uniqueCount
    for (i of uniqueCount) {
    // if this is an item that was not earlier in uniqueCount, 
    // put it into the uniqueChars array
      if (uniqueChars.indexOf(i) == -1) {
        uniqueChars.push(i);
      } 
    }
    // after iterating through all uniqueCount take each item in uniqueChars
    // and compare it with each item in uniqueCount. If this uniqueChars item 
    // corresponds to an item in uniqueCount, increase letterAccumulator by one.
    for (x of uniqueChars) {
      let letterAccumulator = 0;
      for (i of uniqueCount) {
        if (i == x) {letterAccumulator++;}
      }
      console.log(`${x} = ${letterAccumulator}`);
    }
    

提交回复
热议问题