I have a global array
var g = [ "jack", "queen", "king", "10", "ace","7", "8", "9"];
and my array
var my = ["9","king","7","ace"];
This array will be sorted according to the global array g
;
if I sort my array the output will be
["king","ace","7","9"]
I played a lot with arrays but can't accomplish this. Please help me sorting out this issue. Thanks in advance.
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.
You can provide a custom comparison function to JavaScript's Array#sort method. Use the custom comparison function to ensure the sort order: var sortOrder = [2,3,1,4], items = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]; items. sort(function (a, b) { return sortOrder.
Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list.
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 );
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