vinayak shahdeo
vinayak shahdeo

Reputation: 1488

Comparing 2 arrays in java script

How to compare one sorted descending array and one unsorted array in javascript and unsorted array elements location in the sorted one.

so if the number of elements is 7 in sorted array

[100,90,80,70,60,50,40]

and number of elements in unsorted array is 4 unsorted array is

[200,10,55,65]

then the output will be

1
8
6
5

Upvotes: 0

Views: 39

Answers (1)

Mark
Mark

Reputation: 92440

It looks like you want to find the index (one-based) of where each element would fit into the sorted array. You should be able to do this with map() and 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)

Upvotes: 2

Related Questions