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>

9
  • 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. Commented Jun 14, 2016 at 11:49
  • please add some example, raw data and the wanted sorted. Commented Jun 14, 2016 at 11:50
  • 1
    Have you tried something along the lines of arr[0] = {id:1, name: "Nielsen",value: "100,000"}? Commented Jun 14, 2016 at 11:54
  • 1
    You need an Array of objects. You can create array within array but that would not solve your purpose. Commented Jun 14, 2016 at 11:55
  • @NinaScholz I don't understand? I did add that? Commented Jun 14, 2016 at 11:58

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

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.
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.
Awesome, I have filled all the arrays and something "funky" is going on. jsfiddle.net/sbe8yzv0/5 It fails to sort the data and when you click the same button multiple times the sorting jumps around.
Also the alphabetical sorting doesn't seem to want to work?
I have fixed the length function by adding "a.localeCompare(b);" but the alphabetic sorting is still not working - what gives?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.