2

Hi and I'm new to JavaScripts and hopefully anyone of you would help me to figure out. Thanks

My question is how to write a function that expects an array which could contain strings and/or numbers (as well as finite levels of nested arrays of strings and/or numbers), and returns an object which shows the total number of occurences of each unique values.

function functionName() {

 const inputArray = [ 2, 5, 2, 'a', [ 'd', 5, 2, ['b', 1], 0 ], 'A', 5, 'b', 2, 'd' ];
 const outputResult = functionName(inputArray);
}

The key in the object is the unique values found in the array, and the value for each key is the number of occurences for each unique key

The expected result I want is :

 {
'2': 4,
'5': 3,
'a': 1,
'd': 2,
'b': 2,
'1': 1,
'0': 1,
'A': 1,
 }
Becky
  • 73
  • 4

3 Answers3

2

You can try:

const inputArray = [ 2, 5, 2, 'a', [ 'd', 5, 2, ['b', 1], 0 ], 'A', 5, 'b', 2, 'd' ];

const result = inputArray.flat(Infinity).reduce((acc, item) => (acc[item] = (acc[item] || 0) + 1, acc), {})

console.log(result)
Christian Carrillo
  • 2,751
  • 2
  • 9
  • 15
0

You need to recursiely get occurences of each value, like implemented in calculateOccurences:

    const calculateOccurences = function(inputArray, outputResult){
           inputArray.forEach(function(value){
                    if(typeof(value)==='number' || typeof(value)==='string'){
                          outputResult[value] = outputResult[value] ? outputResult[value]+1 : 1;
                    }else if (Array.isArray(value)){
                       calculateOccurences(value, outputResult);
                    }
           })
    }
    
    const inputArray = [ 2, 5, 2, 'a', [ 'd', 5, 2, ['b', 1], 0 ], 'A', 5, 'b', 2, 'd' ];
    const outputResult = {}
    calculateOccurences(inputArray, outputResult ); 
    console.log(outputResult);

Assuming that numbers would be present in type number and not string or that 2 and '2' should be treated the same while calulating occurences.

mangesh
  • 511
  • 8
  • 24
0

In this case it's easier if you convert array into string.

var input = [ 2, 5, 2, 'a', [ 'd', 5, 2, ['b', 1], 0 ], 'A', 5, 'b', 2, 'd' ];

//conver intput into string and replace ',' characters
var stringInput = input.toString().replace(/,/g,'');

var output = {};

//counting
for (var i = 0; i < stringInput.length; i++) {
    var element = stringInput[i];
    output[element] = output[element] ? output[element] + 1 : 1;
}

console.log(output);
Masoud Keshavarz
  • 2,166
  • 9
  • 36
  • 48