Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript sorting array based on another array

Tags:

javascript

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.

like image 301
Shahid Karimi Avatar asked Jun 06 '13 10:06

Shahid Karimi


People also ask

How do you sort an array of objects in JavaScript based on another array?

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.

How do you sort an array of objects based on another array of objects?

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.

How do I sort two arrays together?

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.


1 Answers

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 );
like image 112
VisioN Avatar answered Oct 07 '22 23:10

VisioN