locked
how to reorder arrays in a particular order -using jquery/js RRS feed

  • Question

  • User668774724 posted

    Hi All,
    I have an array like this below:-
    Code below

      var animal= ["Tiger","Cat","Elephant"];
    
        //order array not being used below but thinking of maybe i could use it to order the arrays above
        var order =["1","2","3"];
        $.each(animal, function (key, items) {
                 
    if (items !== null) { //i can get keys here ..0,1,2,3 console.log(key); //i can get item values here ..Tiger, Cat Elephant console.log(items); //appending it to a h2 element here but i would like it to go in a particular order(Not asc or desc) // I want Elephant to be first and then Tiger and then Cat.. //In this order Elephant,Tiger and then Cat $('#contacts').prepend($('<h2 class="disabled" id="tabheader">' + items + '</h2>')); //} } }

    What i want to achieve is :-
    append it to a h2 element  as above  but i would like it to go in a particular order(Not asc or desc)
    I want Elephant to be first and then Tiger and then Cat..
    In this order Elephant,Tiger and then Cat etc..

    Any ideas how this can be achieved?
    Thanks in Advance

    Tuesday, August 11, 2020 6:53 AM

Answers

  • User1535942433 posted

    Hi naijacoder74,

    Accroding to your description, as far as I think,you could create a temp array.And then you could traverse the given array and put all elements at their correct place in temp[] using order[]. Finally copy temp[] to animals[].

    More details,you could refer to below codes:

      <script>
            $(function () {
                var animal = ["Tiger", "Cat", "Elephant"];
    
                //order array not being used below but thinking of maybe i could use it to order the arrays above
                var order = ["1", "0", "2"];
    
                var temp = [];
    
                for (var i = 0; i < animal.length; i++) {
                    temp[order[i]] = animal[i];
                };
                Array.prototype.splice.apply(animal, [0, animal.length].concat(temp));
                $.each(animal, function (key, items) {
    
                    if (items !== null) {
    
                        //i can get keys here ..0,1,2,3 
                        console.log(key);
                        //i can get item values here ..Tiger, Cat Elephant 
                        console.log(items);
    
                        //appending it to a h2 element here but i would like it to go in a particular order(Not asc or desc)
                        // I want Elephant to be first and then Tiger and then Cat..
                        //In this order Elephant,Tiger and then Cat
    
                        $('#contacts').prepend($('<h2 class="disabled" id="tabheader">' + items + '</h2>'));
    
                        //}  
    
                    }
                })
            })
    
        </script>

    Result:

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 12, 2020 8:06 AM
  • User1535942433 posted

    Hi naijacoder74,

    Accroding to your description,I don't know how you add these data.

    Since you don't post your codes,I create a test.I push data into Test array.Foreach the Test array and push them into two arrays.One array is to put name,and another is lastname.

    Just like this:

    var Test=["Test1", "Test2"];
                var xCoordinates = [];
                var yCoordinates = [];
                Test.push("Test1", "Test1", "Test1", "Test1");
                for (var j = 0; j < Test.length; j++) {
                    if (j % 2 == 0)
                        xCoordinates.push(Test[j]);
                    else
                        yCoordinates.push(Test[j]);
    
                }
                 var result = []
    
                    function mapper(key, values) {
                        for (var i = 0; i < values.length; i++) {
                            if (result[i] === undefined) {
                                result[i] = {};
                            }
                            result[i][key] = values[i];
                        }
                    }
    
                    mapper("Name", xCoordinates);
                    mapper("LastName", yCoordinates);
    
                    console.log(JSON.stringify(result));

    Result:

    If you think these answers are helpful to you,you could mark them.

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 13, 2020 8:04 AM

All replies

  • User475983607 posted

    Add a sort property to the data so you can order the items as you wish.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

    <script>
        var animals = [
            { value: 2, animal: "Tiger" },
            { value: 3, animal: "Cat" },
            { value: 1, animal: "Elephant" },
        ]
    
        animals.sort(function (a, b) {
            return a.value - b.value;
        });
    
        $.each(animals, function (key, item) {
            $('#contacts').append($('<h2 class="disabled" id="tabheader">' + item.animal + '</h2>'));
        });
    
    </script>

    Tuesday, August 11, 2020 11:07 AM
  • User668774724 posted

    Thanks mgebhard for the reply.
    But how can i turn this array

    var animal= ["Tiger","Cat","Elephant"];

    to

    var animals = [
            { value: 2, animal: "Tiger" },
            { value: 3, animal: "Cat" },
            { value: 1, animal: "Elephant" },
        ]

    My original array is generated dynamically through rest api.
    Hope this makes sense

    Thanks in Advance

    Wednesday, August 12, 2020 12:36 AM
  • User475983607 posted

    My original array is generated dynamically through rest api.

    There's no magic solution for sorting strings when you want a sort order other than alpha.  Fix the design by adding a sort order property to the dynamic results.  

    Wednesday, August 12, 2020 1:10 AM
  • User1535942433 posted

    Hi naijacoder74,

    Accroding to your description, as far as I think,you could create a temp array.And then you could traverse the given array and put all elements at their correct place in temp[] using order[]. Finally copy temp[] to animals[].

    More details,you could refer to below codes:

      <script>
            $(function () {
                var animal = ["Tiger", "Cat", "Elephant"];
    
                //order array not being used below but thinking of maybe i could use it to order the arrays above
                var order = ["1", "0", "2"];
    
                var temp = [];
    
                for (var i = 0; i < animal.length; i++) {
                    temp[order[i]] = animal[i];
                };
                Array.prototype.splice.apply(animal, [0, animal.length].concat(temp));
                $.each(animal, function (key, items) {
    
                    if (items !== null) {
    
                        //i can get keys here ..0,1,2,3 
                        console.log(key);
                        //i can get item values here ..Tiger, Cat Elephant 
                        console.log(items);
    
                        //appending it to a h2 element here but i would like it to go in a particular order(Not asc or desc)
                        // I want Elephant to be first and then Tiger and then Cat..
                        //In this order Elephant,Tiger and then Cat
    
                        $('#contacts').prepend($('<h2 class="disabled" id="tabheader">' + items + '</h2>'));
    
                        //}  
    
                    }
                })
            })
    
        </script>

    Result:

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 12, 2020 8:06 AM
  • User668774724 posted

    Thanks yij sun for the reply and that did the trick.
    I have one question for you though regarding arrays

    I have this array :-

            var Test = ["Test1", "Tes2"]

    But would like to turn it into the below. I would like to add new properties/fields  Name and LastName

     var Test2 = [{ Name:"Test1", LastName: "Test2" },
            { Name: "Test1", LastName: "Test1" },
            { Name: "Test1", LastName: "Test1" }]

    Hope it makes sense and thanks in advance



    Thursday, August 13, 2020 5:00 AM
  • User1535942433 posted

    Hi naijacoder74,

    Accroding to your description,I don't know how you add these data.

    Since you don't post your codes,I create a test.I push data into Test array.Foreach the Test array and push them into two arrays.One array is to put name,and another is lastname.

    Just like this:

    var Test=["Test1", "Test2"];
                var xCoordinates = [];
                var yCoordinates = [];
                Test.push("Test1", "Test1", "Test1", "Test1");
                for (var j = 0; j < Test.length; j++) {
                    if (j % 2 == 0)
                        xCoordinates.push(Test[j]);
                    else
                        yCoordinates.push(Test[j]);
    
                }
                 var result = []
    
                    function mapper(key, values) {
                        for (var i = 0; i < values.length; i++) {
                            if (result[i] === undefined) {
                                result[i] = {};
                            }
                            result[i][key] = values[i];
                        }
                    }
    
                    mapper("Name", xCoordinates);
                    mapper("LastName", yCoordinates);
    
                    console.log(JSON.stringify(result));

    Result:

    If you think these answers are helpful to you,you could mark them.

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 13, 2020 8:04 AM
  • User668774724 posted

    Thanks yij sun

    Friday, August 14, 2020 2:18 AM