0

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?

Nazmul Hasan
  • 67
  • 1
  • 7

4 Answers4

1

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)
xMayank
  • 1,875
  • 2
  • 5
  • 19
0

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)
Siva K V
  • 10,561
  • 2
  • 16
  • 29
0

Using localeCompare()

const array = ['12GB', '2GB', '4GB', '6GB']

const result = array.sort((a, b) => a.localeCompare(b, 'en', {numeric: true}))

console.log(result)
User863
  • 19,346
  • 2
  • 17
  • 41
0

Using parseInt:

array = ['12GB', '2GB', '4GB', '6GB']

array.sort((a, b) => parseInt(a) - parseInt(b))

console.log(array)
SLePort
  • 15,211
  • 3
  • 34
  • 44