Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question