javascript 数组索引按值升序
javascript array index ascending by value value
我有一个包含以下值的数组:
坟墓 = [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
请问是否可以这样转换:
tomb[5] = 0
tomb[2] = 1
tomb[6] = 2
tomb[3] = 3
tomb[0] = 4
tomb[4] = 5
tomb[1] = 6
我想在for循环中使用这个数组值,但之前我必须从最小值开始增加到最大值。所以我想得到一个从最小到最大的数组索引列表。
const arr = [4, 6, 1, 3, 5, 0, 2];
const min = Math.min.apply(null, arr);
const index = arr.indexOf(min);
console.log(index);
只需使用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)
)
使用 array.sort
和 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)
您可以获得数组的键并根据给定数组的值对索引进行排序。
const
array = [4, 6, 1, 3, 5, 0, 2],
indices = [...array.keys()].sort((a, b) => array[a] - array[b]);
console.log(...indices);
我有一个包含以下值的数组:
坟墓 = [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
请问是否可以这样转换:
tomb[5] = 0
tomb[2] = 1
tomb[6] = 2
tomb[3] = 3
tomb[0] = 4
tomb[4] = 5
tomb[1] = 6
我想在for循环中使用这个数组值,但之前我必须从最小值开始增加到最大值。所以我想得到一个从最小到最大的数组索引列表。
const arr = [4, 6, 1, 3, 5, 0, 2];
const min = Math.min.apply(null, arr);
const index = arr.indexOf(min);
console.log(index);
只需使用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)
)
使用 array.sort
和 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)
您可以获得数组的键并根据给定数组的值对索引进行排序。
const
array = [4, 6, 1, 3, 5, 0, 2],
indices = [...array.keys()].sort((a, b) => array[a] - array[b]);
console.log(...indices);