Coder
Coder

Reputation: 223

push the object to array, according to order number in javascript

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.

Upvotes: 1

Views: 1269

Answers (1)

xfx
xfx

Reputation: 1948

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);
});

Upvotes: 5

Related Questions