13

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.

1 Answer 1

38

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 );

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

1 Comment

Is there possibly a lodash version of this answer now? I want to see if it's faster but I've no idea what's happening here, so I can't replicate it.

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.