I am trying to create a function that creates an object and counts the number duplicates per number in an array. For example if I have an array that is [1,2,2,2,3,3] my function should return 3 because there are two duplicates of 2 and one duplicate of 3. So I wrote a function that I thought was clever. I decided to create a mapping of frequences of each element. By setting the creation of each new property i.e. unique number in the array equal to -1. For some reason when I do this I get property values that are all equal to zero. I am getting two different sets of results from the two functions below.
function DistinctListV1(arr) {
var mapping = {};
for(var i = 0; i < arr.length; i++){
if(!mapping[arr[i]]){
mapping[arr[i]] = 0; //Difference here
}
mapping[arr[i]] += 1;
}
return mapping
}
function DistinctListV2(arr) {
var mapping = {};
for(var i = 0; i < arr.length; i++){
if(!mapping[arr[i]]){
mapping[arr[i]] = -1; //Difference here
}
mapping[arr[i]] += 1;
}
return mapping
}
DistinctListV1([1,2,2,3,3,3])
=> { '1': 1, '2': 2, '3': 3 }
DistinctListV2([1,2,2,3,3,3])
=> { '1': 0, '2': 0, '3': 0 }
Right now I am only concerned about creating an object with this mapping. Thanks for reading.
Edit:
=> DistinctListV3([1,2,2,3,3,3])
function DistinctListV3(arr) {
var mapping = {};
for(var i = 0; i < arr.length; i++){
if(!mapping[arr[i]]){
mapping[arr[i]] = 100; //Difference here
}
mapping[arr[i]] += 1;
}
return mapping
}
DistinctListV3([1,2,2,3,3,3])
=> { '1': 101, '2': 102, '3': 103 }
Using this example, leads me to believe something is going on when I use -1 as the place to start incrementing.
'1' == 1. I'd usereducewithindexOf