0

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
5
  • 5
    How did you get 1 8 6 5 for your output..? I'm not sure what you mean Commented Aug 15, 2018 at 19:07
  • 3
    Why will the output be 1 8 6 5? Commented Aug 15, 2018 at 19:07
  • Is that output supposed to be something like the index at which you'd need to insert the new elements? It's not, exactly, because JS is zero-based, but it looks as though it's something like that. Commented Aug 15, 2018 at 19:10
  • when 200 is encountered in array it is sent at index 1 which makes the array 200 100 90 80 70 60 50 40.for 10 it goes to end of array makes it at position 8.for 55 it goes to position 6 and for 65 it goes to position 5.Kindly do not make changes to the original array. I just want to know the index of the other array elements in previous one Commented Aug 15, 2018 at 19:59
  • Please review How to Ask. Commented Aug 15, 2018 at 20:41

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

can you please elaborate the return part??
Sure @vinayak_shahdeo thats a ternary operator. It says if ind === -1 just return the length of the array +1 otherwise return the ind +1. ind will be -1 if the number you're looking at is smaller than all items int the array (such as 10 in this example). In that case findIndex() doesn't find the index because there are no smaller elements. So it returns -1. The ternary operator lets us test for that special case and return the right value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.