Sort the array of objects by the length of the property

advertisements

I have this array:

var itemList = [
    {
        image: "images/home.jpg",
        name: "Home"
    },
    {
        name: "Elvis",
    },
    {
        name: "Jonh"
    },
    {
        image: "images/noah.jpg",
        name: "Noah"
    },
    {
        name: "Turtle"
    }
]

My question is. How can I organize the array to objects with image property come first, so that it looks like this:

var itemList = [
    {
        image: "images/home.jpg",
        name: "Home"
    },
    {
        image: "images/noah.jpg",
        name: "Noah"
    },
    {
        name: "Elvis",
    },
    {
        name: "Jonh"
    },
    {
        name: "Turtle"
    }
]


This code put at the beginning elements that have the property 'image'. Other elements stay in the same order.

function compare(a,b) {
   if ('image' in a) {
       return 1;
   } else if ('image' in b) {
      return -1;
   } else {
      return 0;
   }
}

itemList.sort(compare);