Reputation: 73
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,
}
Upvotes: 2
Views: 103
Reputation: 2234
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);
Upvotes: 0
Reputation: 521
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.
Upvotes: 0
Reputation: 2761
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)
Upvotes: 2