0

I have a puzzle,

input

var a = ['a', 'b', 'c', 'd'],
    b = [1, 0, 3, 2];

output

['b', 'a', 'd', 'c']

My solution looks like this

function _sort(array, rules) {
  var i, len = rules.length, res = []

  if (array.length !== len) {
    return null; 
  }

  for (i = 0; i < len; i++) {
    res[rules[i]] = array[i];
  }

  return res;
}

How can improve this algorithm ?

1
  • 1
    I don't understand your desired output Commented Aug 4, 2014 at 17:38

3 Answers 3

1

You can do this:

var a = ['a', 'b', 'c', 'd'],
    b = [1, 0, 3, 2];

function mySort(array, rules) {
    var sorted = [];

    for (var i=0; i< rules.length; i++) {
        sorted[rules[i]] = array[i];
    }

    return sorted;
}

mySort(a, b);

> ["b", "a", "d", "c"]
Sign up to request clarification or add additional context in comments.

Comments

0

If you convert it to an array of arrays ([[1,'a'],[0,'b'],[3,'c'],[2,'d']]), which shouldn't be difficult, you can then call Javascript's built-in array.sort() method to sort it.

Comments

0

Pure JS solution

var result = b.map(function(idx) { 
    return a[idx]; 
});

I would use some library like lodash or underscore

var result = _.map(b, function(idx) {
    return a[idx];
});

I would also note it is usually better to run a benchmark on a decently large data set. There is overhead when running a benchmark and as the data gets larger the less this overhead effects the results.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.