mutate an array to match a new index array

Benchmark created on


Description

for example, input string array ['a','b','c','d','e'] and new index array ['3','4','0','2','1'], expected output is ['c','e','d','a','b']

Setup

var list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'],
      newIndexes = [3, 2, 9, 7, 24, 6, 13, 27, 17, 5, 14, 1, 23, 16, 4, 0, 10, 26, 12, 8, 11, 29, 21, 18, 15, 22, 19, 20, 28, 25];

Test runner

Ready to run.

Testing in
TestOps/sec
move the elements in the array
var i = 0,
  len = list.length,
  memo = new Array(len),
  tmp;

for (i = 0; i < len; i++) {

  if (memo[i]) {
    continue;
  }

  if (i !== newIndexes[i]) {
    tmp = list[i];
    list[i] = list[newIndexes[i]];
    list[newIndexes[i]] = tmp;
    memo[newIndexes[i]] = true;
  }
}
ready
create a new array and replace the original elements
var i = 0,
  len = list.length,
  tmp = new Array(len);


for (i = 0; i < len; i++) {
  tmp[newIndexes[i]] = list[i];
}

[].splice.apply(list, [0, len].concat(tmp));
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.