L
L
leyarthemes2019-07-09 08:04:09
JavaScript
leyarthemes, 2019-07-09 08:04:09

How to shuffle an array over an array of indices?

Hello everyone, tell me a cross-browser way to shuffle an array by indexes. For example, I have an array and I have an array of indices . The output should be - . Thank you. [100, 200, 300, 400, 500][0, 3, 1, empty, 2][100, 400, 200, empty, 300]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-07-09
@leyarthemes

there is an array of indices <...> should be -[0, 3, 1, empty, 2]
What, like this - empty? Well, keep:
for (let i = 0; i < indexes.length; i++) {
  if (indexes.hasOwnProperty(i)) {
    arr.push(arr[indexes[i]]);
  } else {
    arr.length++;
  }
}
arr.splice(0, arr.length - indexes.length);

If we abandon this idiocy with empty (let there be something non-numeric in the index array, null for example; and undefiend will be substituted into the original array, respectively), then
arr.splice(0, arr.length, ...indexes.map(i => arr[i]))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question