# Javascript array sort Method problem?

**URL:** <https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624>\
**Category:** Bugs\
**Created:** [February 8, 2015, 12:35pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624 "2015-02-08T12:35:55Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![Arash](https://avatars.discourse-cdn.com/v4/letter/a/da6949/32.png) [@Arash](https://discourse.codecombat.com/u/Arash)\
**Post date:** [February 8, 2015, 12:35pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/1 "2015-02-08T12:35:56Z")

</div>

i used beneath code for “mad-maxer-sells-out” but beside have error for missing semicolon it is not sort properly I want to know any one know why.

```python
loop {
    var closestGold = null;
    var minGoldDist = Infinity;
    var coinIndex = 0;
    var i = 0;
    var coins = this.findItems();
    // Find the closest coin that is gold.
    // Remember that gold coins have a value of 3.
    if (coins){
   coinSort = coins.sort (function(a, b) {
  return a.distanceTo(this) - b.distanceTo(this)});
 
while(i < coinSort.length){
    coin = coinSort[i];
    i++;
    if (coin.value == 3){
    x = coin.pos.x;
    y = coin.pos.y;
    this.moveXY(x, y); 
    }
}
}
}

```

---

<div class="post-metadata">

**Author:** ![J\_F\_B\_M](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.codecombat.com/j_f_b_m/32/2756_2.png) [@J\_F\_B\_M](https://discourse.codecombat.com/u/J_F_B_M)\
**Post date:** [February 8, 2015, 1:25pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/2 "2015-02-08T13:25:33Z")

</div>

Usually I fix indentations in JS-Code simply and enclose them in a code block.

This however is a wonderful example why **Indentations are _IMPORTANT_.**

If you look in line 11, you can see that there is an semicolon missing. Let’s fix that:

```python
   coinSort = coins.sort (function(a, b) {
  return a.distanceTo(this) - b.distanceTo(this)});

```

becomes

```python
coinSort = coins.sort (function(a, b){
    return a.distanceTo(this) - b.distanceTo(this)
});

```

and, oh wonder, there I see a missing semicolon. Here is the corrected and indented code:

```python
loop {
    var closestGold = null;
    var minGoldDist = Infinity;
    var coinIndex = 0;
    var i = 0;
    var coins = this.findItems();
    // Find the closest coin that is gold.
    // Remember that gold coins have a value of 3.
    if (coins){
        coinSort = coins.sort (function(a, b) {
            return a.distanceTo(this) - b.distanceTo(this);
        });
 
        while(i < coinSort.length){
            coin = coinSort[i];
            i++;
            if (coin.value == 3){
                x = coin.pos.x;
                y = coin.pos.y;
                this.moveXY(x, y); 
            }
        }
    }
}

```

* * *

Despite of that, I’m not 100% certain that passing functions to another function is really working. At least in Python I get problems. But someone else is more qualified to answer this particular question.

---

<div class="post-metadata">

**Author:** ![Arash](https://avatars.discourse-cdn.com/v4/letter/a/da6949/32.png) [@Arash](https://discourse.codecombat.com/u/Arash)\
**Post date:** [February 8, 2015, 1:57pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/3 "2015-02-08T13:57:43Z")

</div>

thanks an now it has error “don’t make function within a loop” and not work again. and what about passing function in function can deal as object? what you suggest ?

---

<div class="post-metadata">

**Author:** ![J\_F\_B\_M](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.codecombat.com/j_f_b_m/32/2756_2.png) [@J\_F\_B\_M](https://discourse.codecombat.com/u/J_F_B_M)\
**Post date:** [February 8, 2015, 2:03pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/4 "2015-02-08T14:03:31Z")

</div>

Well, the solution to that is given in the error-message:

```python
function sortFunction(a, b) {
    return a.distanceTo(this) - b.distanceTo(this); 
}

loop {
    // code before
    coinSort = coins.sort (sortFunction);
    // code after
}

```

---

<div class="post-metadata">

**Author:** ![Arash](https://avatars.discourse-cdn.com/v4/letter/a/da6949/32.png) [@Arash](https://discourse.codecombat.com/u/Arash)\
**Post date:** [February 8, 2015, 5:12pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/5 "2015-02-08T17:12:44Z")

</div>

thanks a lot, but i don’t know why is not sort proper this is my code i use say to show  
for me the one with distance 24.\* is problem other is correct sorted

```python
// Coins here disappear after a few seconds!
// Get all the gold coins before they vanish.
function sortFunction(a, b) {
    return a.distanceTo(this) - b.distanceTo(this); 
}

loop {
    var closestGold = null;
    var minGoldDist = Infinity;
    var coinIndex = 0;
    var i = 0;
    var coins = this.findItems();
    // Find the closest coin that is gold.
    // Remember that gold coins have a value of 3.
    if (coins){
        coinSort = coins.sort (sortFunction);
        while(i < coinSort.length){
            coin = coinSort[i];
            i++;
    
            aa= this.distanceTo(coin);
            this.say(aa);
            this.say(i);
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![nick](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.codecombat.com/nick/32/784_2.png) [@nick](https://discourse.codecombat.com/u/nick)\
**Post date:** [February 9, 2015, 9:48pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/6 "2015-02-09T21:48:19Z")

</div>

JavaScript is a bit weird. When you make a new function, `this` refers to that function, not your hero any more. So you can do something like this instead:

```javascript
var self = this;
function sortFunction(a, b) {
    return a.distanceTo(self) - b.distanceTo(self);
}

```

---

<div class="post-metadata">

**Author:** ![Arash](https://avatars.discourse-cdn.com/v4/letter/a/da6949/32.png) [@Arash](https://discourse.codecombat.com/u/Arash)\
**Post date:** [February 10, 2015, 4:48pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/7 "2015-02-10T16:48:50Z")

</div>

thanks all but the problem is not solve do you think i should immigrant to python can u give me some good references for JS

---

<div class="post-metadata">

**Author:** ![nick](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.codecombat.com/nick/32/784_2.png) [@nick](https://discourse.codecombat.com/u/nick)\
**Post date:** [February 10, 2015, 11:18pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/8 "2015-02-10T23:18:56Z")

</div>

What is your current code, and what is still going wrong?

---

<div class="post-metadata">

**Author:** ![Arash](https://avatars.discourse-cdn.com/v4/letter/a/da6949/32.png) [@Arash](https://discourse.codecombat.com/u/Arash)\
**Post date:** [February 11, 2015, 8:23am UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/9 "2015-02-11T08:23:05Z")

</div>

thanks a lot dear nick. it is actually in 6 coins one of them is not sort appropriately.

```python
// Coins here disappear after a few seconds!
// Get all the gold coins before they vanish.

var self = this;
function sortFunction(a, b) {
    return self.distanceTo(a) - self.distanceTo(b);
}

loop {
    var closestGold = null;
    var minGoldDist = Infinity;
    var coinIndex = 0;
    var i = 0;
    var coins = this.findItems();
    // Find the closest coin that is gold.
    // Remember that gold coins have a value of 3.
    if (coins){
        coinSort = coins.sort (sortFunction);
        while(i < coinSort.length){
            coin = coinSort[i];
            i++;
            if (coin.value == 3){
                x = coin.pos.x;
                y = coin.pos.y;
                this.moveXY(x, y); 
            }
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![nick](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.codecombat.com/nick/32/784_2.png) [@nick](https://discourse.codecombat.com/u/nick)\
**Post date:** [February 12, 2015, 1:17am UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/10 "2015-02-12T01:17:18Z")

</div>

Yup, looks like it straight up doesn’t work. It doesn’t even seem to be calling your sort function.

---

<div class="post-metadata">

**Author:** ![sotonin](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.codecombat.com/sotonin/32/24089_2.png) [@sotonin](https://discourse.codecombat.com/u/sotonin)\
**Post date:** [February 12, 2015, 1:42am UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/11 "2015-02-12T01:42:46Z")

</div>

sorting doesnt return anything. it modifies the original object.

so

```python
coins.sort(sortFunction);

```

is all you need. then your coins object should be sorted in whatever way your sorting method sorts it.

if that doesn’t work then it has something to do with trying to call those methods in your sort function. in my sort function i instead pre populate my coins array by tacking the distance on to each coin as a property then inside my coin sort method i do it like this.

```python
function coin_sort(a, b) {  
    return a.distance - b.distance;  
}

```

---

<div class="post-metadata">

**Author:** ![JavaScriptNinja](https://avatars.discourse-cdn.com/v4/letter/j/8edcca/32.png) [@JavaScriptNinja](https://discourse.codecombat.com/u/JavaScriptNinja)\
**Post date:** [July 10, 2015, 4:32am UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/12 "2015-07-10T04:32:44Z")

</div>

Hi there friend, I know this thread is a bit old but I have to ask, why you think it’s “weird” that JavaScript changes what “this” refers to in the definition of a function? I associate the word “this” with the currently scoped block of code. I have a programming background in C# mostly. Maybe, that’s why I don’t find it odd or unusual. In fact, It seems perfectly logical and natural to me.

I actually think it’s weird that JavaScript doesn’t properly change the context of “this” to the local function scope when a function is actually executing. “this” should refer to the function itself when it is executing since it is just another object.

---

<div class="post-metadata">

**Author:** ![J\_F\_B\_M](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.codecombat.com/j_f_b_m/32/2756_2.png) [@J\_F\_B\_M](https://discourse.codecombat.com/u/J_F_B_M)\
**Post date:** [July 11, 2015, 9:13am UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/13 "2015-07-11T09:13:51Z")

</div>

For a long-term programmer this might seem logical, but view it from the side of a newcomer.

```python
this.moveXY(1, 1); // "Global" this

this.foo = function(){
    this.moveXY(1, 2); //Also "global" this
};

var bar = function(){
    this.moveXY(1, 3); //Suddenly not global anymore?!?
};

```

The way the code is displayed suggests it is all one big context. In fact, up until the functions using `this` all over the place was perfectly save. Now, without any warning (literally spoken) you need to wrap your brain around the problem that `this != this`, depending on whether you write it inside the curly brackets or not.

I think it falls in the same area as the indentations in Python. Once you are used to them it is perfectly clear why you need them, but util then it is better guessing whether I should place 4, 8 or maybe 12 Spaces in front of this to magically get it “inside” the if, whatever that means.

---

<div class="post-metadata">

**Author:** ![UltCombo](https://sea2.discourse-cdn.com/flex016/user_avatar/discourse.codecombat.com/ultcombo/32/3822_2.png) [@UltCombo](https://discourse.codecombat.com/u/UltCombo)\
**Post date:** [July 18, 2015, 7:18pm UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/14 "2015-07-18T19:18:55Z")

</div>

> [@J\_F\_B\_M](#):
>
> Despite of that, I’m not 100% certain that passing functions to another function is really working.

It really isn’t working. See these discussions:

- [[JavaScript] Can't use ES5 Array methods · Issue #2874 · codecombat/codecombat · GitHub](https://github.com/codecombat/codecombat/issues/2874)
- [Functions do not seem to work in Lua · Issue #2635 · codecombat/codecombat · GitHub](https://github.com/codecombat/codecombat/issues/2635#issuecomment-90320467)

---

<div class="post-metadata">

**Author:** ![AdrianCgw](https://avatars.discourse-cdn.com/v4/letter/a/ac8455/32.png) [@AdrianCgw](https://discourse.codecombat.com/u/AdrianCgw)\
**Post date:** [February 12, 2016, 7:38am UTC](https://discourse.codecombat.com/t/javascript-array-sort-method-problem/2624/15 "2016-02-12T07:38:13Z")

</div>

See my post about how to get past the limitations of callbacks:

> [@Use of Programmaticon V's array methods](https://discourse.codecombat.com/t/use-of-programmaticon-vs-array-methods/6745):
>
> For those of you determined enough to get the Programmaticon V the array library may still be a puzzle: How to use them and what are their advantages? Simple answer: it allows you to generate some very light and fast code. Good if your level code keeps crashing or if you are running into HEL (hard execution limit, currently 3 million) I will explain how to use the most important functions in the library: map, filter and reduce An appendix will list all the array methods grouped by categori…
