按属性值对对象数组进行排序

1693

我使用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属性以升序降序排序的函数?


最快的方法是使用isomorphic sort-array模块,它在浏览器和Node中都可以本地运行,支持任何类型的输入、计算字段和自定义排序顺序。 - Lloyd
相关:按对象属性值对数组进行数字排序 - Sebastian Simon
35个回答

0
 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


0

如果您想使用,我最近编写了一个通用函数来管理此事。

/**
 * Sorts an object into an order
 *
 * @require jQuery
 *
 * @param object Our JSON object to sort
 * @param type Only alphabetical at the moment
 * @param identifier The array or object key to sort by
 * @param order Ascending or Descending
 *
 * @returns Array
 */
function sortItems(object, type, identifier, order){

    var returnedArray = [];
    var emptiesArray = []; // An array for all of our empty cans

    // Convert the given object to an array
    $.each(object, function(key, object){

        // Store all of our empty cans in their own array
        // Store all other objects in our returned array
        object[identifier] == null ? emptiesArray.push(object) : returnedArray.push(object);

    });

    // Sort the array based on the type given
    switch(type){

        case 'alphabetical':

            returnedArray.sort(function(a, b){

                return(a[identifier] == b[identifier]) ? 0 : (

                    // Sort ascending or descending based on order given
                    order == 'asc' ? a[identifier] > b[identifier] : a[identifier] < b[identifier]

                ) ? 1 : -1;

            });

            break;

        default:

    }

    // Return our sorted array along with the empties at the bottom depending on sort order
    return order == 'asc' ? returnedArray.concat(emptiesArray) : emptiesArray.concat(returnedArray);

}

0
一个简单的代码:

    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"
        }
    ];

    let sortByPrice = homes.sort(function (a, b) 
    {
      return parseFloat(b.price) - parseFloat(a.price);
    });

    for (var i=0; i<sortByPrice.length; i++)
    {
      document.write(sortByPrice[i].h_id+' '+sortByPrice[i].city+' '
       +sortByPrice[i].state+' '
       +sortByPrice[i].zip+' '+sortByPrice[i].price);
      document.write("<br>");
    }


-1
function sortByProperty(home){
    return home.price
}

sortByProperty 函数通过价格获取属性。将来,您可能希望按“邮政编码”或甚至字符串值“城市”对数据进行排序。您只需更改上述函数中的 home.price 即可。

// if you want descending order change this to false
// if you are on react.js you could set this with useState
const ascending=true
// Initially "b" is the index-1 item and "a" is the index-0 item
homes.sort((a,b)=>{
     //initially 0th index
     const first=sortByProperty(a)
     // initially 1st index 
     const second=sortByProperty(b)
     
     // if you multiply by -1 it will be descending 
     const sortOrder=ascending ? 1 : -1
     if (typeof first==="number"){
            return (first-second) * sortOrder
    } else {
           // this will compare the string values
           return (first.localeCompare(second)) * sortOrder
    }
})

-3

如果您不想使用任何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);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接