1

I have the following array of objects:

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

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

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

BUT i have the variablefilterType 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?

Nikola Pavicevic's user avatar
Nikola Pavicevic
23.6k9 gold badges30 silver badges52 bronze badges
askedJul 14, 2021 at 15:14
Bowis's user avatar
3
  • 1
    Does this answer your question?Sort array of objects by string property valueCommentedJul 14, 2021 at 15:18
  • @Wyck no, because in that example you know the key of the object property, in my case I need to search for this key based on the user input, which is thefilterType variableCommentedJul 14, 2021 at 15:19
  • 1
    Are you looking for computed property names ? this.products.sort((a, b) => parseFloat(b[filterType]) - parseFloat(a[filterType]));CommentedJul 14, 2021 at 15:21

2 Answers2

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

Does this answer your question?

answeredJul 14, 2021 at 15:21
Sanket Shah's user avatar
Sign up to request clarification or add additional context in comments.

Comments

1

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)

answeredJul 14, 2021 at 15:27
Nikola Pavicevic's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.