I have an array with storage. I want sort it. Please take a look below:
array = ['12GB', '2GB', '4GB', '6GB']
array.sort() = ['12GB', '2GB', '4GB', '6GB']
expected_output_array = ['2GB', '4GB', '6GB', '12GB']
how can I achieve this?
I have an array with storage. I want sort it. Please take a look below:
array = ['12GB', '2GB', '4GB', '6GB']
array.sort() = ['12GB', '2GB', '4GB', '6GB']
expected_output_array = ['2GB', '4GB', '6GB', '12GB']
how can I achieve this?
You can use Array.sort
and just split on GB
, get the first item, and when subtracting the strings are converted to numbers anyway
You can try this.
const array = ['12GB', '2GB', '4GB', '6GB']
const ans = array.sort(function(a,b) {
return a.split('GB')[0] - b.split('GB')[0];
});
console.log(ans)
In the sort method, extract the values and compare them. (without that it will treat as strings and not numbers)
array = ['12GB', '2GB', '4GB', '6GB']
array.sort((a, b) => {
const getValue = str => Number(str.replace("GB", ""));
return getValue(a) - getValue(b);
})
console.log(array)
Alternatively
array = ['12GB', '2GB', '4GB', '6GB']
array.sort((a, b) => parseInt(a) - parseInt(b))
console.log(array)
Using localeCompare()
const array = ['12GB', '2GB', '4GB', '6GB']
const result = array.sort((a, b) => a.localeCompare(b, 'en', {numeric: true}))
console.log(result)
Using parseInt
:
array = ['12GB', '2GB', '4GB', '6GB']
array.sort((a, b) => parseInt(a) - parseInt(b))
console.log(array)