1

Below array i have 5 objects, with random order value, need to arrange the array as per the order key in object

i want push each object another array as per order.

  var array =  [
    {

        "name": {
            "text": "javascript"
        },
        "order": {
            "text": "4"
        }

    },
    {

        "name": {
            "text": "angualr js"
        },
        "order": {
            "text": "2"
        }
    },
 {

        "name": {
            "text": "Ios"
        },
        "order": {
            "text": "3"
        }
    },
 {

        "name": {
            "text": "PHP"
        },
        "order": {
            "text": "5"
        }
    }, {

        "name": {
            "text": "C"
        },
        "order": {
            "text": "5"
        }
    }
]

can any explain how to follow the logic.

1 Answer 1

5

Just sort the array with Array.prototype.sort, it accepts a function as parameter to compare two items.

array.sort(function(a, b) {
  return parseInt(a.order.text, 10) - parseInt(b.order.text, 10);
});
Sign up to request clarification or add additional context in comments.

4 Comments

Could you at least give some explanation about your code?
I think return (+a.order.text) - (+b.order.text) might be good as well.
@JinyoungKim which works, but not a "natural" way. People expect parseInt return an integer, but won't expect +"string" return integer.
I'd note that this solution will change the order of items in array. So, if @Galaba really wants to have another array sorted, that's what is needed: var sortedArray = array.slice(); sortedArray.sort(function(a, b) { return parseInt(a.order.text, 10) - parseInt(b.order.text, 10); });

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.