简体   繁体   中英

Sort array of objects based on string parameter

I have the following array of objects:

   [
     {
       "id" : 1,
       "pricePerDay" : 50,
     }, 
     {
       "id" : 2,
       "pricePerDay" : 70   
     }
   ]

Based on the user input from ai want to filter either ASC or DESC on the pricePerday . Obviously this would work with:

 this.products.sort((a, b) => parseFloat(b.pricePerDay) - parseFloat(a.pricePerDay));

BUT i have the variable filterType which now contains the string 'pricePerDay' . How can I use this variable to search the array of objects to properties that have the same key and sort this array based on that key?

this.products.sort((a, b) => parseFloat(b[filterType]) - parseFloat(a[filterType]));

Does this answer your question?

You can change filterType to field that you want and acs to false if you want desc order

 const arr = [ { "id": 1, "pricePerDay": 50, }, { "id": 2, "pricePerDay": 70 } ] let filterType = 'pricePerDay' let asc = false const res = arr.sort((a, b) => { if (asc) { return parseFloat(a[filterType]) - parseFloat(b[filterType]) } else { return parseFloat(b[filterType]) - parseFloat(a[filterType]) } }); console.log(res)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM