Function that compares and array with its numerically sorted version in ascending order. Return the sum of the square differences between each term of the two arrays.
Expample:
For the array a= [2,3,1], the sorted version is b=[1,2,3],
.the sum of the square differences is (2-1)2 + (3-2)2 + (1-3)2 = 6
. or in terms of array elements (a[0]-b[0])2 + (a[1]-b[1])2 + (a[2]+b[2])2 = 6
const arr = [2, 3, 1];
function myFunction(arr) {
var newarr = [];
var a = arr;
var b = arr;
var sum = 0;
b.sort(function(a, b) {
return a - b
});
for (var i = 0; i < b.length; i++) {
var sub = a[i] - b[i];
sub = sub * 2;
sum += sub;
newarr.push(sum);
}
return newarr;
}
console.log(myFunction(arr));