数组排序不起作用

数组排序不起作用

本文介绍了数组排序不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我试图排序但它似乎没有工作。数组中的某些对象具有 orderNum 属性,我将其定位为排序。但并非所有对象都具有此属性。

I have an array of objects that I am trying to sort but it does not seem to be working. Some objects in the array have a orderNum property which I am targeting to sort. But not all objects have this property.

我希望将带有 orderNum 属性的对象排序到数组中的顶部位置。

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

这是我尝试过的小提琴:

Here is a fiddle to what i have tried: http://jsfiddle.net/7D8sN/

这是我的javascript:

Here is my javascript:

var data = {
  "attributes": [
    {
        "value": "123-456-7890",
        "name": "phone"
    },
    {
        "value": "[email protected]",
        "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);


推荐答案

检查排序函数中是否存在该属性。

Check if the 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;
});

这篇关于数组排序不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:37