1

I'm trying to sort array with custom values, by it's integer value. There is my array:

[ 'a>46', 'a>86', 'h>78' ]

And desired output:

[ 'a>46', 'h>78', 'a>86' ]

Note: the largest possible value to be found in my array is 90.

I'm trying this way:

  var newarr = [];
  var max = 91;
          for (let u = 0; u < array.length; u++) {
            var nmbr = parseInt(array[u].replace(/\D/g,'')); // get integer of array element

            if (nmbr < max) {       // if element is lower than current highest value
              max = nmbr;
              newarr[0] = array[u];  // assign it to the beggining of new array
            } else {   // else put it at as the next newarr element

              newarr[newarr.lenght+1] = array[u];
            }

          }

Output:

[ 'a>46', <1 empty item>, 'a>86' ]
1
  • what is supposed to be minutsy can you add a snippet? Commented Aug 28, 2018 at 21:50

3 Answers 3

2

I'd recommend using Array.prototype.sort().

var array = ["a>46", "h>78", "a>86"]
array.sort(function(a, b) {
  var number_a = parseInt(a.replace(/\D/g,''));
  var number_b = parseInt(b.replace(/\D/g,''));
  return number_a - number_b;
});

Outputs ["a>46", "h>78", "a>86"]


if you wanna learn more about how this actually works I recommend checking out the compare function example here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Basically: if you return zero, then a and b are equal. if you return a negative number that means a is less than b. if you return a positive number that means a is greater than b.

Sign up to request clarification or add additional context in comments.

2 Comments

This works, but the replace method return ">46" which includes the > sign.
may need to consider this kind of case var array = ["a2>46", "h1>78", "a0>86"]
1

To achieve expected reult, use below option of using array sort function

var array = [ 'a>46', 'a>86', 'h>78' ]


console.log(array.sort((a,b) => a.substring(2) - b.substring(2)));

https://codepen.io/nagasai/pen/eLdYKz?editors=1010

2 Comments

Note that this answer uses implicit conversion, which may be confusing at first glance.
as per SO, comparison happens by integer values after '>' , using parseInt will do and even if it is not used , it work due to implicit conversion as mentioned by you
0

JavaScript comes with a built in method to sort arrays.

const array = [ 'a>46', 'a>86', 'h>78' ];

array.sort((a, b) => {
  a = Number.parseInt(a.replace(/\D/g, ''), 10);
  b = Number.parseInt(b.replace(/\D/g, ''), 10);
  return a - b;
});

console.log(array);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseInt

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.