Sorting an Array Related to Another Array

Javascript - sort array based on another array

One-Line answer.

itemsArray.sort(function(a, b){  
return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});

Or even shorter:

itemsArray.sort((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));

Sort one array the same way as another array JavaScript

You could sort the keys of the first array based on their value. This will return an array with indices of the array sorted based on the value of numbers array. Then use map to get the sorted values based on the indices

const numbers = [2, 4, -2, 4, 1, 3],      alphabets = ["a", "b", "c", "d", "e", "f"]
const keys = Array.from(numbers.keys()).sort((a, b) => numbers[a] - numbers[b])
const sortedNumbers = keys.map(i => numbers[i]), sortedAlphabets = keys.map(i => alphabets[i])
console.log( sortedNumbers, sortedAlphabets)

Sorting an array related to another array

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

Sort an array in the same order of another array

Use indexOf() to get the position of each element in the reference array, and use that in your comparison function.

var reference_array = ["ryan", "corbin", "dan", "steven", "bob"];var array = ["bob", "dan", "steven", "corbin"];array.sort(function(a, b) {  return reference_array.indexOf(a) - reference_array.indexOf(b);});console.log(array); // ["corbin", "dan", "steven", "bob"]

Sort an array of objects based on another array of ids

Ramda really shines for these types of problems.

Where the size of the data is small, we can use a simple reduce function, and indexOf helper.

// match id of object to required index and insert
var sortInsert = function (acc, cur) {
var toIdx = R.indexOf(cur.id, a);
acc[toIdx] = cur;
return acc;
};

// point-free sort function created
var sort = R.reduce(sortInsert, []);

// execute it now, or later as required
sort(b);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]

This works well for small(ish) data sets but the indexOf operation on every iteration through the reduction is inefficient for large data sets.

We can remedy this by tackling the problem from the other side, lets use groupBy to group our objects by their id, thus creating a dictionary lookup (much better!). We can then simply map over the required indexes and transform them to their corresponding object at that position.

And here is the solution using this approach:

var groupById = R.groupBy(R.prop('id'), b);

var sort = R.map(function (id) {
return groupById[id][0];
});

sort(a);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]

Finally, this is yet another solution, which is very succinct:

R.sortBy(R.pipe(R.prop('id'), R.indexOf(R.__, a)))(b);
// [ { id: 2 }, { id: 3 }, { id: 1 }, { id: 4 } ]

I love the way you can compose functions with behaviour and separate the algorithm from the data upon which it acts using Ramda. You end up with very readable, and easy to maintain code.

javascript sorting array based on another array

One possible way:

var g = ['jack', 'queen', 'king', '10', 'ace', '7', '8', '9'];var my = ['9', 'king', '7', 'ace'];
my.sort(function(a, b) { return g.indexOf(a) - g.indexOf(b);});
console.log( my );

Java: Sorting an array based on another array with indexOf method

It seems you expect indexOrder.indexOf(s) to always be equal to s (since your List was initialized to [0, 1, 2, 3], where the index of s is s).

While this is true in your original indexOrder List, this may no longer true when Collections.sort starts swapping elements of your List.

In order not to rely on the ordering of indexOrder while you are sorting it, you can create a copy of that List:

List<Integer> copy = new ArrayList<>(indexOrder);
Collections.sort(indexOrder, Comparator.comparing((Integer s) -> indexes[copy.indexOf(s)]));

Sort an array based on another array

You can do it using the map function on the second array where you find the element matching the number

Example

const questions = [
{
id: 1,
data: {
question: "What is your name?"
}
},
{
id: 2,
data: {
question: "How old are you?"
}
},
{
id: 3,
data: {
question: "Where do you leave?"
}
},
{
id: 4,
data: {
question: "Foo"
}
},
{
id: 5,
data: {
question: "Bar"
}
},
]

const newOrder = [2,1,5,4,3]

const newQuestionsOrdered = newOrder.map(x => questions.find(question => question.id === x))

console.log(newQuestionsOrdered)

How do I reorder another array based on a sorted array Java?

If we sort an array of indexes instead of the original array we get the order of the elements:

Integer[] nums = {8,1,2,2,3};

Integer[] order = new Integer[nums.length];
Arrays.setAll(order, i->i);
Arrays.sort(order, (a, b) -> nums[a] - nums[b]);

System.out.println(Arrays.toString(order));

Gives:

[1, 2, 3, 4, 0]

This represents the required permutation of values in the 2nd array.

We can now use a standard algorithm to permute an array according to a specified order:

static <T> void reorder(T[] a, Integer[] order)
{
for(int i=0; i<a.length; i++)
{
while(order[i] != i)
{
swap(a, order[i], i);
swap(order, order[i], i);
}
}
}

static <T> void swap(T[] a, int i, int j)
{
T tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}

Putting this together

Integer[] nums = {8,1,2,2,3};

Integer[] order = new Integer[nums.length];
Arrays.setAll(order, i->i);
Arrays.sort(order, (a, b) -> nums[a] - nums[b]);

Integer[] count = {0,1,1,3,4};
reorder(count, order);

System.out.println(Arrays.toString(count));

Output:

[4, 0, 1, 1, 3]


Related Topics



Leave a reply



Submit