admin管理员组文章数量:1290952
I want JavaScript
function, that receive an array as input and output the indices of the array in a order which if value is max it's index should be at [0]
of new array, second max [1]
and so on ...
for example: [3, 4, 5, 1, 2]
as input should give [2,1,0,4,3]
output
I code this function but I want a way with one for loop or one map
function
const maxValueIndexes = (array) => {
if (array.length === 0) return [];
const indexedArray = array.map((value, index) => ({value, index }));
indexedArray.sort((a, b) => b.value - a.value);
return indexedArray.map((item) => item.index);
}
Is there any better way in terms of time complexity ??
for example O(n)
answer
if there is solution please write it for me
I want JavaScript
function, that receive an array as input and output the indices of the array in a order which if value is max it's index should be at [0]
of new array, second max [1]
and so on ...
for example: [3, 4, 5, 1, 2]
as input should give [2,1,0,4,3]
output
I code this function but I want a way with one for loop or one map
function
const maxValueIndexes = (array) => {
if (array.length === 0) return [];
const indexedArray = array.map((value, index) => ({value, index }));
indexedArray.sort((a, b) => b.value - a.value);
return indexedArray.map((item) => item.index);
}
Is there any better way in terms of time complexity ??
for example O(n)
answer
if there is solution please write it for me
Share Improve this question edited 22 hours ago Areza-s1011 asked 23 hours ago Areza-s1011Areza-s1011 155 bronze badges 3 |2 Answers
Reset to default 1You could get the keys of the array and sort according of value.
(And yes, an interator is a loop.)
const
array = [3, 4, 5, 1, 2],
result = [...array.keys()].sort((i, j) => array[j] - array[i]);
console.log(result); // [2, 1, 0, 4, 3]
If you want to achieve this with only one map
, you can do it by maintaining a list of indices and sorting them based on the corresponding values in the array. Here's how you can do it with a single map
function:
function getSortedIndices(arr) {
return arr
.map((_, index) => index) // Create an array of indices [0, 1, 2, ...]
.sort((a, b) => arr[b] - arr[a]); // Sort indices based on the values in the original array
}
// Example usage:
const input = [3, 4, 5, 1, 2];
const output = getSortedIndices(input);
console.log(output); // Output: [2, 1, 0, 4, 3]
本文标签:
版权声明:本文标题:javascript, better way for get indices of numrical array in decrsing order as new array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739210789a2148671.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
.sort
has a time complexity of at leastO(n log n)
. The additional loops don't change anything. They have a time complexity ofO(n)
.O(n log n + n) == O(n log n) + O(n) == O(n log n)
– jabaa Commented 22 hours ago