I have two arrays, x
and y
, where y is the value of the tens of every element in x
. Now, I want to sort y
. But, the order of y
will be different of x
's. So, I can't tell after sorting which element in y
was related to, for instance, x[0]
.
I want a "double sorting" maybe.
Method 1 (Using Sorting and Binary Search)Create a temporary array temp of size m and copy the contents of A1[] to it. Create another array visited[] and initialize all entries in it as false. visited[] is used to mark those elements in temp[] which are copied to A1[]. Initialize the output index ind as 0.
const arr1 = ['d','a','b','c'] ; const arr2 = [{a:1},{c:3},{d:4},{b:2}]; We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.
Relative Sort Array. Easy. Given two arrays arr1 and arr2 , the elements of arr2 are distinct, and all elements in arr2 are also in arr1 . Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2 .
Array.Sort
has an overload that accepts two arrays; one for the keys, and one for the items. The items of both are sorted according to the keys
array:
int[] keys = { 1, 4, 3, 2, 5 }; string[] items = { "abc", "def", "ghi", "jkl", "mno" }; Array.Sort(keys, items); foreach (int key in keys) { Console.WriteLine(key); // 1, 2, 3, 4, 5 } foreach (string item in items) { Console.WriteLine(item); // abc, jkl, ghi, def, mno }
So in your case, it sounds like you want:
Array.Sort(y,x); // or Sort(x,y); - it isn't 100% clear
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With