I got an array that with different values and I'd like to calculate a percentage value that symbolizes the similarity of all it's elements using maybe a threshold property.
An array could look like this:
var array = [42.98, 42.89, 42.91, 42.98, 42.88] // should return nearly 100%
var array = [42.98, 22.89, 42.91, 42.98, 42.88] // should return maybe 80%
var array = [42.98, 332.89, 122.91, 5512.98, -12.88] // should return nearly 0%
So 100% stands if all elements are the same ... and 0 % stands for the case the elements are way different. The adjustment is set by editing the threshold
I do not really know how to solve the problem (I'm an absolutely newbie) - however this is all I got so far and obviously it is not working that way:
function checkSimilarity(array, threshold) {
var sum = array.reduce((a, b) => a + b, 0),
percentage = 0;
for (var i =0; i< array.length; i++) {
var diff = (sum / array.length) * i
percentage += diff
}
return percentage * (threshold/100)
}
Any help how to solve my problem of creating a working algorithm would be very appreciated!
for ... inloop gives you the indexes into the array, not the value. Don't usefor ... infor plain arrays; usefor ... of, or a simpleforloop with an index variable, or.forEach()