user3730696
user3730696

Reputation:

Sort array by index which specified in another array, best algorithm

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 ?

Upvotes: 0

Views: 68

Answers (3)

jlonganecker
jlonganecker

Reputation: 1198

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.

Upvotes: 0

Marco Bonelli
Marco Bonelli

Reputation: 69477

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"]

Upvotes: 1

Larkeith
Larkeith

Reputation: 434

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.

Upvotes: 0

Related Questions