search

Home  >  Q&A  >  body text

Sort an array of objects based on property values

<p>I obtained the following objects using AJAX and stored them in an array: </p> <pre class="brush:php;toolbar:false;">var homes = [ { "h_id": "3", "city": "Dallas", "state": "Texas", "zip": "75201", "price": "162500" }, { "h_id": "4", "city": "Beverly Hills", "state": "California", "zip": "90210", "price": "319250" }, { "h_id": "5", "city": "New York", "state": "New York State", "zip": "00010", "price": "962500" } ];</pre> <p>How can I create a function using JavaScript that sorts objects in ascending<strong> or </strong>descending order using only the <code>price</code> property? </p>
P粉561749334P粉561749334471 days ago560

reply all(2)I'll reply

  • P粉956441054

    P粉9564410542023-08-22 11:15:39

    This is a more flexible version that allows you to create reusable sort functions and sort by any field.

    const sort_by = (field, reverse, primer) => {
    
      const key = primer ?
        function(x) {
          return primer(x[field])
        } :
        function(x) {
          return x[field]
        };
    
      reverse = !reverse ? 1 : -1;
    
      return function(a, b) {
        return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
      }
    }
    
    
    //现在您可以按任何字段排序...
    
    const 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"}];
    
    // 按价格从高到低排序
    console.log(homes.sort(sort_by('price', true, parseInt)));
    
    // 按城市排序,不区分大小写,按A-Z排序
    console.log(homes.sort(sort_by('city', false, (a) =>  a.toUpperCase()
    )));

    reply
    0
  • P粉493534105

    P粉4935341052023-08-22 11:08:15

    Sort homes by price in ascending order:

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

    Or after ES6 version:

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

    Some documentation can be found here.

    To sort in descending order you can use

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

    reply
    0
  • Cancelreply