0

Is there a function in JavaScript that allows me to change the index? For example, I have 4 values ​​in an array:

var arr = [10, -20, 20, 30]

Now I want to set the lowest value as the first index and the following after the same pattern. The index should be for the example above:

[-20, 10, 20, 30]
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
JCss
  • 99
  • 9

2 Answers2

2

It sounds like you want to sort the array. The default JS sort uses string-based comparisons. You need to provide your own comparator function for numeric comparisons:

var arr = [10, -20, 20, 30]

arr.sort((i, j) => i - j)

console.log(arr)
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
2

You could get the index of the smallest value, splice it and unshift this value.

The result does not alter the order of other elements, like with sort.

var array = [10, -20, 20, 30],
    index = array.reduce((r, v, i, a) => a[r] < v ? r : i, 0);

array.unshift(array.splice(index, 1)[0]);

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392