Home > Software design >  javascript array index ascending by value value
javascript array index ascending by value value

Time:02-16

I have an array which one including below values:

tomb = [4, 6, 1, 3, 5, 0, 2]

tomb[0] = 4
tomb[1] = 6
tomb[2] = 1
tomb[3] = 3
tomb[4] = 5
tomb[5] = 0
tomb[6] = 2

Can I ask is possible to convert like this:

tomb[5] = 0
tomb[2] = 1
tomb[6] = 2
tomb[3] = 3
tomb[0] = 4
tomb[4] = 5
tomb[1] = 6

I would like to use in for loop this array values, but before I have to start from the minimum and increase to the biggest one. So I would like get a array index list from minimum to maximum.

const arr = [4, 6, 1, 3, 5, 0, 2];
const min = Math.min.apply(null, arr);
const index = arr.indexOf(min);
console.log(index);

CodePudding user response:

You could get the keys of the array and sort the indices by the values of the given array.

const
    array = [4, 6, 1, 3, 5, 0, 2],
    indices = [...array.keys()].sort((a, b) => array[a] - array[b]);

console.log(...indices);

CodePudding user response:

Try this one by using array.sort and array.indexOf

const arr = [4, 6, 1, 3, 5, 0, 2];
const newarr = arr.slice()
const arrindex = []
newarr.sort()
newarr.forEach(i=>{
arrindex.push(arr.indexOf(i))
})
console.log(arrindex)

CodePudding user response:

Just use Array.sort()

const arr = [4, 6, 1, 3, 5, 0, 2];
const sorted = arr
    .map((value, index) => ({ index, value }))
    .sort((a, b) => a.value - b.value)
console.log(
    sorted.map(entry => entry.index),
    sorted.map(entry => entry.value)
)

  • Related