-1

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));
Barmar
  • 741,623
  • 53
  • 500
  • 612
leesa
  • 3
  • 1

1 Answers1

0

Assigning arrays doesn't make copies. So a, b, and arr are all the same array, and you're just subtracting a number from itself, always getting zero. You need to make a copy of the array in the other variable.

You're also not squaring correctly, it should be sub * sub, not sub * 2.

You're supposed to return sum. There's no need for newArr.

const arr = [2, 3, 1];

function myFunction(arr) {
  var sorted = [...arr]; // make copy
  sorted.sort(function(a, b) {
    return a - b
  });

  var sum = 0;
  for (var i = 0; i < sorted.length; i++) {
    var sub = arr[i] - sorted[i];
    sub = sub * sub;
    sum += sub;
  }
  return sum;

}

console.log(myFunction(arr));
Barmar
  • 741,623
  • 53
  • 500
  • 612