如何比较javascript中一个排序的降序数组和一个未排序的数组以及排序后的数组中未排序的数组元素位置。
所以如果排序数组中的元素数为7
[100,90,80,70,60,50,40]
未排序数组中的元素数为4,未排序数组为
[200,10,55,65]
然后输出将为
1
8
6
5
答案 0 :(得分:2)
您似乎想找到每个元素适合排序数组的位置的索引(基于1)。您应该可以使用map()
和findIndex()
来做到这一点:
let arr = [100,90,80,70,60,50,40]
let a2 = [200,10,55,65]
let indexes = a2.map(n => {
// find the first place in arr where it's less than n
let ind = arr.findIndex(i => i < n)
// if n wasn't found, it is smaller than all items: return length + 1
return (ind === -1) ? arr.length + 1 : ind + 1
})
console.log(indexes)