I'am pretty new to JavaScript and i have this exercise that have been bugging me for a some hours now.
I want to write a Javascript function that expects an array which could contain string and/or numbers (as well as finite levels of nested arrays of strings and/or numbers), and returns a Javascript object which shows the total number of occurences of each unique values.
Something like this
var myArray = [ 1, 2, 1, 'a', [ 'd', 5, 6 ], 'A', 2, 'b', 1, 'd' ];
var myResult = myFunction( myArray );
Then it should return something like this
yourResult = {
1: 3,
2: 2,
'a': 1,
'd': 2,
5: 1,
6: 1,
'A': 1,
'b': 1,
}
So far what i have is this. I dont know how to create the object but this is not working at all. It ads all the values in the array
Array.prototype.contains = function(v) {
for(var i = 0; i < this.length; i++) {
if(this[i] === v) return true;
}
return false;
};
Array.prototype.unique = function() {
var arr = [];
for(var i = 0; i < this.length; i++) {
if(this[i] instanceof Array) {
for(var j = 0; i < this[i].length; j++){
if (!arr.contains(this[i][j])){
arr.push(this[i][j]);
}
}
}
if(!arr.contains(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
var myArray = [1,3,4,2,1,[1,2,3,6],2,3,8];
var myResult = duplicates.unique();
console.log(myResult);
myArray.flatten().count(). A.unique()method would typically only remove duplicates, but not count occurences.