JSFiddle - React, Tailwind, and code Playground
by chanaka1
JavaScript
var array = ['my', 2, 3, '3','3', 'youurs', 2, 6, { myProp : 1 }, { myProp : 1 }];
var length = array.length;
//The array ArrayWithUniqueValues will contain only one value for each entry of array
var ArrayWithUniqueValues = [];
//Object objectCounter will store the distinct values of array as property and
//the number of times they are present in array as values
var objectCounter = {};
for (i = 0; i < length; i++) {
//First i stringify the current member of the Array, this will be the key that i will use to check if the value is already present
var currentMemboerOfArrayKey = JSON.stringify(array[i]);
//This is the value that i will sstore only once in ArrayWithUniqueValues
var currentMemboerOfArrayValue = array[i];
//I check if the property currentMemboerOfArrayKey of the object is undefined, which is the default value of unset properties
if (objectCounter[currentMemboerOfArrayKey] === undefined){
//If the property is undefined, this is the first time i have this value in the array, so i add it to ArrayWithUniqueValues
ArrayWithUniqueValues.push(currentMemboerOfArrayValue);
//I set the current key of the object to one: this is both for counting reasons and for avoiding duplicates because
//the next time objectCounter[currentMemboerOfArrayKey] === undefined will be false and the value will not be added to ArrayWithUniqueValues
objectCounter[currentMemboerOfArrayKey] = 1;
}else{
//The key was already present, augment the counter by one
objectCounter[currentMemboerOfArrayKey]++;
}
}
/*
If i output the value of objectCounter to the console i will have:
Value Number of times present
2 2
3 1
6 1
"3" 2
"my" 1
"youurs" 1
{"myProp":1} 2
*/
console.log(objectCounter);
/* If i output the value of ArrayWithUniqueValues to the console i will have
["my", 2, 3, "3", "youurs", 6, Object {...