I’m trying to sort an array of objects based on a property value, but the property is a string that includes a number. For example, I have an array of objects like this:
const data = [
{ name: 'Item 1', value: '2 apples' },
{ name: 'Item 2', value: '10 oranges' },
{ name: 'Item 3', value: '1 banana' },
{ name: 'Item 4', value: '5 strawberries' }
];
I want to sort the array by the numeric value in the value property, so that the sorted array looks like this:
[ { name: 'Item 3', value: '1 banana' }, { name: 'Item 1', value: '2 apples' }, { name: 'Item 4', value: '5 strawberries' }, { name: 'Item 2', value: '10 oranges' }]
Here is my code which is not working
data=data.sort((a,b) => b.value-a.value)
One solution can be: "split value on space then get number from 0th index and then compare". Is there any better way of sorting?
4
Answers
You could use
parseInt
orparseFloat
to convert thevalue
into a number and then do the sorting algorithm:You can use
replace
and regex to extract numbers to sort:The
extractNumber
function extracts the first number found in a string using a regular expression (/d+/
) and then returns it as an integer usingparseInt()
. If no number is found, it returns 0. Then the function is used inside the sort method to compare the numbers.Try with above logic, it should work