Count different values present in an array

Count different values present in an array

Method 1:

If you know the values which are present in an array, and those known values are in another array for reference. If you got confused, let it go I am sharing an example now:

Example:

const knownVal = ['sun', 'earth', 'moon'];
const countingArray = ['sun','moon','moon','sun','earth'];

Now, you can simply check by checking through looping with countingArray, if an element present in knownValue is equal to countingArray[i].

Didn't understand?

See the code:

let countMap = new Map();

for(let n of knownVal){
  let value = 0;
  for(let i = 0; i<countingArray.length; i++){
    if(n == countingArray[i]){
      countMap.set(n,++value);
    }
  }
}

In the above code, as we check for each value equal to the countArray's element we update for a unique element in the Map Data structure.

It will store it like:

{
  'sun': 2,
  'earth': 1,
  'moon': 2
}

Use Map methods to access the values like:

  • countMap.get(key) to access a particular value,
  • const keyArray = [...countMap.keys()], to get keys in an array,
  • const valueArray = [...countMap.values()], to get values in an array.

Method 2:

If you don't have any particular array for the reference and have only countingArray, then there is also a logic or algorithm to operate.

  • Now mapping through countingArray we will track if we got the same value previously, if not then set the value to 'Map' and its value as 1 initially.
  • If we have already tracked the key to the Map then increase its value by 1 on each match.

CODE:

let countMap = new Map();
countinArray.map((el)=>{
        if(countMap.has(el){
                countMap.set(el, countMap.get(el)+1);
        }
        else{
                countMap.set(el,1);
        }
});

It will store it like:

{
  'sun': 2,
  'earth': 1,
  'moon': 2
}

This can be used while manipulating and accessing different types of data to get results accordingly, this is how data structures and algorithms work to give results. People hyped over these terms to scare but they are nothing much to help you find the data accordingly.

Method 2, many time complexity can be achieved by applying different algorithmic logic which can be found here at GFG.