4

I have this array:

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

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"
    }
]
double-beep
  • 5,031
  • 17
  • 33
  • 41
Caio Kawasaki
  • 2,894
  • 6
  • 33
  • 69
  • 1
    possible duplicate of [Sort array of objects by string property value in JavaScript](http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – Andreas Aug 28 '15 at 13:36
  • @Andreas No, I need to check if the property exists and not order them. – Caio Kawasaki Aug 28 '15 at 13:37
  • 2
    Are those names correct? you have `image`, `imagem`, `name` and `nome`? – Nicholas Robinson Aug 28 '15 at 13:41
  • @NicholasRobinson Wops, corrected... – Caio Kawasaki Aug 28 '15 at 13:42
  • Possible duplicate of [howto sort an array with objects by property value length?](https://stackoverflow.com/questions/16002562/howto-sort-an-array-with-objects-by-property-value-length), but your question was unclear, since the accepted answer actually doesn't check length at all and will order the elements with an `image` property in the order they show up in the array. – Heretic Monkey Feb 12 '19 at 19:05

3 Answers3

5

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);
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
1

Try this:

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

objs.sort(compare);
Nicholas Robinson
  • 1,359
  • 1
  • 9
  • 20
  • 1
    This is not the situation, but a.image doesn't return true if the property exists, but if the property exists and is value can be evaluated to true. For example if the property exists and the string is null the value is false, if the property is a boolean and the value is false it returns false – Davide Lorenzo MARINO Aug 28 '15 at 13:48
  • 1
    The Ecma said: about boolean conversion of strings: "Return false if argument is the empty String (its length is zero); otherwise return true." Similarly null values are converted to false. – Davide Lorenzo MARINO Aug 28 '15 at 13:54
0

A bit late, but an alternative:

itemList.sort(function(e1,e2){ return  (e1.image === undefined) - (e2.image === undefined); });
Me.Name
  • 12,259
  • 3
  • 31
  • 48