1

I have an array currently only with names because I cannot figure out how to add more information but not make the script sort that data. For every entry in the array I wish to add a number between 1-20 for each, and also a count of how many is named that name. So it would something like 1. Nielsen (100,000). It's only a problem with my second function because I need to sort it by length.

<script>
    var arr = []
    arr[0] = " Nielsen"
    arr[1] = " Jensen"
    arr[2] = " Hansen"
    arr[3] = " Pedersen"
    arr[4] = " Andersen"
    arr[5] = " Christensen"
    arr[6] = " Larsen"
    arr[7] = " Sørensen"
    arr[8] = " Rasmussen"
    arr[9] = " Jørgensen"
    arr[10] = " Petersen"
    arr[11] = " Madsen"
    arr[12] = " Kristensen"
    arr[13] = " Olsen"
    arr[14] = " Thomsen"
    arr[15] = " Christiansen"
    arr[16] = " Poulsen"
    arr[17] = " Johansen"
    arr[18] = " Møller"
    arr[19] = " Mortensen"

    document.getElementById("liste").innerHTML = arr; // Skriver den oprindelige rækkefølge

    function Sorter1() {
        arr.sort(); // Sorter efter aflabetisk rækkefølge
        document.getElementById("liste").innerHTML = arr; // Skriver rækkefølgen
    }

    function Sorter2() {
        arr.sort(function (a, b) {
            return b.length - a.length || // sorter efter længde
                a.localeCompare(b); // Sorter efter aflabetisk rækkefølge
        });
        document.getElementById("liste").innerHTML = arr; // Skriver rækkefølgen
    }
</script>

Thomasdc
  • 55
  • 5
  • I forgot to mention I don't need it to sort the other data only the names, but the other data should also be shown without obscuring the sorting by length and alphabet. – Thomasdc Jun 14 '16 at 11:49
  • please add some example, raw data and the wanted sorted. – Nina Scholz Jun 14 '16 at 11:50
  • 1
    Have you tried something along the lines of `arr[0] = {id:1, name: "Nielsen",value: "100,000"}`? – Angelos Chalaris Jun 14 '16 at 11:54
  • 1
    You need an [Array of objects](http://stackoverflow.com/questions/15742442/declaring-array-of-objects). You can create array within array but that would not solve your purpose. – Rohit416 Jun 14 '16 at 11:55
  • @NinaScholz I don't understand? I did add that? – Thomasdc Jun 14 '16 at 11:58
  • @chalarangelo Not sure. How do I sort by name in the two functions? – Thomasdc Jun 14 '16 at 11:58
  • What do you actually want, explain it clearly please! – Rohit416 Jun 14 '16 at 12:00
  • I want to sort the array by the names currently listed in the array. I also have other data that I wish to show next to the name, this data I only need to show not to be able to be sorted. so ie. i want it to sort the names and then in the HTML it will show "Nielsen, 1. (20000)" followed by Olsen, 14. (20000) etc. – Thomasdc Jun 14 '16 at 12:02
  • Until you have some relation between the names and their corresponding value, it is difficult manage. How you are populating the other data? The ultimate and appropriate solution that i can see for now is the array containing objects. – Rohit416 Jun 14 '16 at 12:13

2 Answers2

2

If I understand you correct you would like to create a multidimensional array and then sort it on the name alphabetically and on character count. If that is correct I would suggest you to create an multidimensional object with the data needed. Then you will be able to sort on the name key and preserve the other information correctly.

Check this out, it may get you in the right direction

var arr = [
    {
    name: 'Nielsen',
    num: 1,
    count: 100
  },
  {
    name: 'Jensenlongest',
    num: 15,
    count: 230
  },
  {
    name: 'Jensenlong',
    num: 13,
    count: 500
  },
  {
    name: 'Jensen',
    num: 2,
    count: 300
  },
  {
    name: 'Hansen',
    num: 5,
    count: 400
  }
]

// Just adds the unsorted arr to the list for demo purpose
updateList(arr)

// On "Sort by length" button click
document.getElementById('sort-by-length').addEventListener('click', function (event) {
    arr.sort(sortNameByLength);
  updateList(arr);
})

// On "Sort alphabetically" button click
document.getElementById('sort-alphabetically').addEventListener('click', function (event) {
    arr.sort(sortNameAlphabetically);
  updateList(arr);
})

// Sort by name alphabetically
function sortNameAlphabetically(a, b) {
    return a.name > b.name
}

// Sort by name length
function sortNameByLength(a, b) {
    return a.name.length - b.name.length
}

// Updates the list according to the current sorting of the arr
function updateList(names) {
  var listHtml = ''

  names.forEach(function (item, index) {
    listHtml += item.name + ', ' + item.num + ' (' + item.count + ')<br>'
  })

  document.getElementById("liste").innerHTML = listHtml
}

https://jsfiddle.net/sbe8yzv0/4/

This will result in a list like this.

Hansen, 5 (400)
Jensen, 2 (300)
Jensenlong, 13 (500)
Jensenlongest, 15 (230)
Nielsen, 1 (100)
  • Almost yea. It needs two function which I have attached to two buttons: The first button sorts the names alphabetically and the second button sorts the name by length and then by alphabet. So if: ABB, ABA and AAB: it would be sorted AAB, ABA, ABB with second function. – Thomasdc Jun 14 '16 at 12:18
  • Ok, then you can just split the sort function into two different functions. The a.length - b.length in one and a.name > b.name in another. – Kristoffer Svanmark Jun 14 '16 at 12:20
  • Awesome, I have filled all the arrays and something "funky" is going on. https://jsfiddle.net/sbe8yzv0/5/ It fails to sort the data and when you click the same button multiple times the sorting jumps around. – Thomasdc Jun 14 '16 at 12:49
  • Also the alphabetical sorting doesn't seem to want to work? – Thomasdc Jun 14 '16 at 13:02
  • I have fixed the length function by adding "a.localeCompare(b);" but the alphabetic sorting is still not working - what gives? – Thomasdc Jun 14 '16 at 13:13
0

You can use an array of complex objects with the data structure you like (just be consistent). Then define your own sort() method that will compare only the name parameter of your objects. Here's a simple example:

var arr = [];
arr[0] = {ID: 1, Name: "Nielsen", Value: "100"};
arr[0] = {ID: 2, Name: "Jensen", Value: "200"};
// Sort based on the second column, 'Name'.
function sortByName(){
    arr.sort(
        function(x, y){
            return x.Name > y.Name; // Compare and sort based on the 'Name' column only.
        }
    );
    console.log(arr[0]);    // If results are correct this is 'Jensen'.
    console.log(arr[1]);    // If results are correct this is 'Nielsen'.
}   

Adapt this to your needs (add the proper columns and data, add the proper variables, make it so that it shows in your page's HTML) and it will do what you want.

Angelos Chalaris
  • 5,882
  • 7
  • 44
  • 65