【问题标题】:Sorting an array of objects by property values按属性值对对象数组进行排序
【发布时间】:2010-11-02 00:43:33
【问题描述】:

我使用 AJAX 获得了以下对象并将它们存储在一个数组中:

var homes = [
    {
        "h_id": "3",
        "city": "Dallas",
        "state": "TX",
        "zip": "75201",
        "price": "162500"
    }, {
        "h_id": "4",
        "city": "Bevery Hills",
        "state": "CA",
        "zip": "90210",
        "price": "319250"
    }, {
        "h_id": "5",
        "city": "New York",
        "state": "NY",
        "zip": "00010",
        "price": "962500"
    }
];

我如何创建一个函数,以仅使用 JavaScript 以 升序 降序顺序通过 price 属性对对象进行排序?

【问题讨论】:

  • 最快的方法是使用同构的sort-array 模块,它可以在浏览器和节点中本地工作,支持任何类型的输入、计算字段和自定义排序顺序。

标签: javascript arrays sorting


【解决方案1】:
 function compareValues(key, order = 'asc') {
  return function innerSort(a, b) {
    if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
      // property doesn't exist on either object
      return 0;
    }

    const varA = (typeof a[key] === 'string')
      ? a[key].toUpperCase() : a[key];
    const varB = (typeof b[key] === 'string')
      ? b[key].toUpperCase() : b[key];

    let comparison = 0;
    if (varA > varB) {
      comparison = 1;
    } else if (varA < varB) {
      comparison = -1;
    }
    return (
      (order === 'desc') ? (comparison * -1) : comparison
    );
  };
}

http://yazilimsozluk.com/sort-array-in-javascript-by-asc-or-desc

【讨论】:

    【解决方案2】:

    如果您不想使用任何sort() 方法,可以使用以下方法

    function sortObj(obj) {
      let numArr = []; //the array which just includes prices as Number
      let sortedObj = [];
      obj.map((x) => {
        numArr.push(Number(x["price"]));
      });
    
      while (numArr.length > 0) { 
        let minIndex = numArr.indexOf(Math.min(...numArr)); //the index of cheapest home in the obj
        numArr.splice(minIndex, 1); 
        sortedObj.push(obj.splice(minIndex, 1)); // splicing cheapest home from Homes Array to sortedObj Array.
      }
    
      console.log(sortedObj);
    }
    
    var homes = [
      {
        h_id: "3",
        city: "Dallas",
        state: "TX",
        zip: "75201",
        price: "162500",
      },
      {
        h_id: "4",
        city: "Bevery Hills",
        state: "CA",
        zip: "90210",
        price: "319250",
      },
      {
        h_id: "5",
        city: "New York",
        state: "NY",
        zip: "00010",
        price: "962500",
      },
    ];
    sortObj(homes);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多