# Question about sorting 2D array

**URL:** <https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347>\
**Category:** Curriculum Help\
**Tags:** javascript\
**Created:** [July 30, 2022, 1:29am UTC](https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347 "2022-07-30T01:29:25Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![admit8490](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/admit8490/32/240085_2.png) [@admit8490](https://forum.freecodecamp.org/u/admit8490)\
**Post date:** [July 30, 2022, 1:29am UTC](https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347/1 "2022-07-30T01:29:25Z")

</div>

Lets say I have 2D array(example will be from one of the code prep challenges).

```auto
let testArr = [
  [88, 'Bowling Ball'],
  [2, 'Dirty Sock'],
  [3, 'Hair Pin'],
  [5, 'Microphone'],
  [3, 'Half-Eaten Apple'],
  [7, 'Toothpaste']
]

```

I want to sort it alphabetically, by the elements with indexes [1](or I can say strings).  
In my research I’ve run into some snippets like this:

```auto
function sortFunction(a, b) {
    if (a[0] === b[0]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}

```

Here they are doing this check:

```auto
    if (a[0] === b[0]) {
        return 0;
    }

```

However I was able to do the same for [Inventory Update](https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/inventory-update) challenge and pass the tests with sorting like below:

```auto
testArr.sort((a, b) => {
    return (a[1] < b[1]) ? -1 : 1;
  }
  );

```

So I skipped _check if equal_  
For now I don’t know, is my solution is good for this kind of tasks in general, or I was just lucky with this particular challenge.

---

<div class="post-metadata">

**Author:** ![admit8490](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/admit8490/32/240085_2.png) [@admit8490](https://forum.freecodecamp.org/u/admit8490)\
**Post date:** [July 30, 2022, 3:02am UTC](https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347/4 "2022-07-30T03:02:27Z")

</div>

I changed sorting like below and its failing tests now. Maybe I misunderstood your suggestion? Link to the challenge in the first post

```auto
function updateInventory(arr1, arr2) {
    for (let newItem of arr2) {
      let isItnewItem = true;
      for (let curItem of arr1) {
        if (curItem[1] === newItem[1]) {
          curItem[0] += newItem[0];
          isItnewItem = false;
          break;
        }
      }
      if (isItnewItem) {
        arr1.push(newItem);
      }
    }
  return arr1.sort((a, b) => {
    return a[1] - b[1];
  }
  );
}

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

updateInventory(curInv, newInv);

```

---

<div class="post-metadata">

**Author:** ![colinthornton](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/colinthornton/32/62129_2.png) [@colinthornton](https://forum.freecodecamp.org/u/colinthornton)\
**Post date:** [July 30, 2022, 3:51am UTC](https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347/5 "2022-07-30T03:51:47Z")

</div>

You’re probably getting NaN, try using the localeCompare method instead.

---

<div class="post-metadata">

**Author:** ![admit8490](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/admit8490/32/240085_2.png) [@admit8490](https://forum.freecodecamp.org/u/admit8490)\
**Post date:** [July 30, 2022, 4:14am UTC](https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347/6 "2022-07-30T04:14:11Z")

</div>

> [@colinthornton](#):
>
> You’re probably getting NaN

I am geting Nan because JS is trying to give me some number for the below?

> [@admit8490](#):
>
> ```auto
> arr1.sort((a, b) => {
> return a[1] - b[1];
> }
> );
> 
> ```

Checked _localeCompare_, that’s definitely an option, thanks.

---

<div class="post-metadata">

**Author:** ![colinthornton](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/colinthornton/32/62129_2.png) [@colinthornton](https://forum.freecodecamp.org/u/colinthornton)\
**Post date:** [July 30, 2022, 5:00am UTC](https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347/7 "2022-07-30T05:00:38Z")

</div>

```javascript
'Bowling Ball' - 'Dirty Sock' // this is NaN

```

A string minus a string is `NaN`. To compare strings you’d have to go character by character and compare the values of `charCodeAt`. Or just use `localeCompare`.

---

<div class="post-metadata">

**Author:** ![admit8490](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/admit8490/32/240085_2.png) [@admit8490](https://forum.freecodecamp.org/u/admit8490)\
**Post date:** [July 30, 2022, 5:18am UTC](https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347/8 "2022-07-30T05:18:58Z")

</div>

Got it.  
One more thing:  
If I run the below:

```auto
let testArr = [
  [88, 'Bowling Ball'],
  [2, 'Dirty Sock'],
  [3, 'Hair Pin'],
  [5, 'Microphone'],
  [3, 'Half-Eaten Apple'],
  [7, 'Toothpaste']
]

console.log(testArr.sort())

/*
Output:

[
  [2, 'Dirty Sock'],
  [3, 'Hair Pin'],
  [3, 'Half-Eaten Apple'],
  [5, 'Microphone'],
  [7, 'Toothpaste'],
  [88, 'Bowling Ball']
]
*/

```

From it I make conclusion, that 2D array, by default, sorted by elements with index 0. I mean testArr[0][0], testArr[1][0] etc

So here in this example it took numbers and compared them(as a strings).  
Am I right about that?

---

<div class="post-metadata">

**Author:** ![colinthornton](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/colinthornton/32/62129_2.png) [@colinthornton](https://forum.freecodecamp.org/u/colinthornton)\
**Post date:** [July 30, 2022, 9:35am UTC](https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347/9 "2022-07-30T09:35:41Z")

</div>

> **[Array.prototype.sort() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description)**
>
> The sort() method of Array instances sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences...

> If `compareFunction` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order.

So, the arrays got stringified and then compared as strings. If you had something with 9 items you’d see that it comes after the 88 bowling balls.

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/freecodecamp/original/3X/e/1/e1c433102e34b46dfaa3e15d13ab9a514b127078.svg) [@system](https://forum.freecodecamp.org/u/system)\
**Post date:** [January 28, 2023, 9:36pm UTC](https://forum.freecodecamp.org/t/question-about-sorting-2d-array/536347/10 "2023-01-28T21:36:11Z")

</div>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.
