0

I'm new to JavaScript and feel like I must be missing something fundamental here!

I'm creating a function which sorts a list of integers list and returns the minimum value listSort[0].

function sortNumber(a,b) {
    return a - b;
}

var min = function(list){
    console.log(list[0]);
    var listSort = list.sort(sortNumber);
    console.log(list[0]);
    console.log(listSort[0]);
    return list[0];
}

Can anyone explain why the value of list[0] changes after list.sort(sortNumber) is assigned to listSort ?

Thanks!

  • [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort): "The sort() method sorts the elements of an array **in place** and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points." – Andreas Aug 24 '16 at 16:09

3 Answers3

0

To get the minimum value of an Array, better use Math.min

var list = [4,2,4,2,6,5,2,4,3,5,2];

var min = Math.min.apply(null, list);
baao
  • 71,625
  • 17
  • 143
  • 203
0

If i'm right, it's because when you use your assignment, you are executing list.sort(sortNumber) and so list change as per the assignment function.

Sooo... read like this : - list.sort(sortNumber) => List change - list is assigned to listSort

Despite this fact, I think you're going to far to find the min value. :P

Aks
  • 395
  • 3
  • 11
  • Is there away of assigning the value without executing the sort? Or perhaps I just need to do `listSort = list; listSort.sort(sortNumber);` of course - I probably should do away with listSort altogether in this example, but mostly I want to understand how the assignment works – Chilliontop Aug 24 '16 at 16:27
  • Hm.. I don't really know if there is a way to assign the value without executing the sort. (Except for your proposal, this is what I will do in this case) One way is to rewrite a function that will return the value like "sort(list, sortNumber)" where you can do all the treatments. – Aks Aug 24 '16 at 16:34
  • @Chilliontop `listSort = list; listSort.sort(sortNumber);` is the same as `listSort = list.sort(sortNumber)` (relating to the result) -> [Primitive value vs Reference value](https://stackoverflow.com/questions/13266616/primitive-value-vs-reference-value) – Andreas Aug 24 '16 at 17:34
0

The sort() function directly changes the array to which is applied. For example:

myArray.sort();

directly changes the content of myArray. If you do not want to change the content of the original array you need to use a cloning function:

function mySortingFunction(list){
   var newList = myCloningFunction(list);
   newList.sort();
   return newList;
}

There are several ways to clone an array: Javascript fastest way to duplicate an Array - slice vs for loop

If you use AngularJS you can simply write:

var newList = angular.copy(list);
Community
  • 1
  • 1
Luigi C.
  • 990
  • 12
  • 22