我使用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()方法,可以使用以下方法

函数sortObj(obj){设numArr=[]//仅包含价格作为Number的数组让sortedObj=[];对象映射((x)=>{numArr.push(数字(x[“价格”]));});而(numArr.length>0){让minIndex=numArr.indexOf(数学最小(…numArr))//obj最便宜的住宅指数numArr.拼接(最小索引,1);排序对象推送(对象拼接(minIndex,1));//将最便宜的家庭从Homes Array拼接到sortedObj Array。}console.log(sortedObj);}var家=[{h_id:“3”,城市:“达拉斯”,状态:“TX”,邮编:“75201”,价格:“162500”,},{h_id:“4”,城市:“贝弗利山”,状态:“CA”,邮编:“90210”,价格:“319250”,},{h_id:“5”,城市:“纽约”,州:“NY”,邮编:“00010”,价格:“962500”,},];sortObj(家);

其他回答

用于字符串排序,以防有人需要,

常量数据Arr={“您好”:[{“id”:114,“关键字”:“zzzzzz”,“地区”:“斯里兰卡”,“supportGroup”:“administrators”,“category”:“类别2”}, {“id”:115,“关键字”:“aaaaa”,“地区”:“日本”,“supportGroup”:“开发者”,“category”:“类别2”}]};const sortArray=dataArr['hello'];console.log(sortArray.sort((a,b)=>{如果(a.region<b.region)返回-1;如果(a.region>b.region)返回1;返回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

仅对于元素值的普通数组:

function sortArrayOfElements(arrayToSort) {
    function compareElements(a, b) {
        if (a < b)
            return -1;
        if (a > b)
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareElements);
}

e.g. 1:
var array1 = [1,2,545,676,64,2,24]
output : [1, 2, 2, 24, 64, 545, 676]

var array2 = ["v","a",545,676,64,2,"24"]
output: ["a", "v", 2, "24", 64, 545, 676]

对于对象数组:

function sortArrayOfObjects(arrayToSort, key) {
    function compareObjects(a, b) {
        if (a[key] < b[key])
            return -1;
        if (a[key] > b[key])
            return 1;
        return 0;
    }

    return arrayToSort.sort(compareObjects);
}

e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]

output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]
function sortByProperty(home){
    return home.price
}

sortByProperty按价格获取属性。将来,您可能希望按“zip”或字符串值“city”对数据进行排序。您需要在上面的函数中更改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
    }
})

有了ECMAScript 6,StoBor的答案可以更加简洁:

homes.sort((a, b) => a.price - b.price)