Sort an array of objects by property length

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 an array for objects with image property so that they look like this:

var itemList = [
    {
        image: "images/home.jpg",
        name: "Home"
    },
    {
        image: "images/noah.jpg",
        name: "Noah"
    },
    {
        name: "Elvis",
    },
    {
        name: "Jonh"
    },
    {
        name: "Turtle"
    }
]
+4
source share
3 answers

This code is placed in the initial elements that have a property 'image'. The remaining elements remain 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);
+5
source

Try the following:

function compare(a,b) {
  if (a.image && b.image)
    return 0;
  if (a.image)
    return 1;
  return -1;
}

objs.sort(compare);
+1
source

, :

itemList.sort(function(e1,e2){ return  (e1.image === undefined) - (e2.image === undefined); });
0

All Articles