Not sorted.

I have an array of objects that I am trying to sort, but it does not seem to work. Some objects in the array have a property orderNumthat I configure to sort. But not all objects have this property.

I want the objects with the property to be orderNumsorted to the top positions in the array.

Here is the fiddle for what I tried: http://jsfiddle.net/7D8sN/

Here is my javascript:

var data = {
  "attributes": [
    {
        "value": "123-456-7890",
        "name": "phone"
    },
    {
        "value": "Something@something.com",
        "name": "email"
    },
    {
        "value": "Gotham",
        "name": "city",
        "orderNum": 1
    },
    {
        "value": "12",
        "name": "ID"
    },
    {
        "value": "Batman",
        "name": "Super Hero",
        "orderNum": 2
    }
  ]
};

data.attributes.sort( function (a, b) {
  if (a.orderNum < b.orderNum) {
    return -1;
  }
  if (a.orderNum > b.orderNum) {
    return 1;
  }

  return 0;
});

console.log(data);
+4
source share
4 answers

Check if a property exists in your sort function.

data.attributes.sort( function (a, b) {
    if ((typeof b.orderNum === 'undefined' && typeof a.orderNum !== 'undefined') || a.orderNum < b.orderNum) {
        return -1;
    }
    if ((typeof a.orderNum === 'undefined' && typeof b.orderNum !== 'undefined') || a.orderNum > b.orderNum) {
        return 1;
    }

    return 0;
});
+8
source

, undefined. false, return 0 .

data.attributes.sort( function (a, b) {
  if (a.orderNum === undefined || a.orderNum < b.orderNum) {
    return -1;
  }
  if (b.orderNum === undefined || b.orderNum < a.orderNum) {
    return 1;
  }

  return 0;
});
+3

You can check if each object has property c hasOwnProperty("orderNum"), and then sorts them accordingly. If someone has this and the other does not, then one is placed first with him. I made the assumption that you sorted with orderNum in ascending order.

JSFiddle: http://jsfiddle.net/dshell/RFr5N/

data.attributes.sort( function (a, b) {
    if ((a.hasOwnProperty("orderNum")) && (b.hasOwnProperty("orderNum")))
    {
        return a.orderNum - b.orderNum;
    }
    else if (a.hasOwnProperty("orderNum"))
    {
        return -1;
    }
    else if (b.hasOwnProperty("orderNum"))
    {
        return 1;
    }

    return 0;
});
+2
source

What you need is to "normalize" your input:

data.attributes.sort( function (a, b) {
   var aOrderNum = ( a.orderNum === undefined ) ? -1 : a.orderNum ;
   var bOrderNum = ( b.orderNum === undefined ) ? -1 : b.orderNum ;
   return aOrderNum - bOderNum;
 });
0
source

Source: https://habr.com/ru/post/1538119/


All Articles