Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform and reorder array in JavaScript?

Is there an elegant way to reorder JavaScript array? For example, says I have an array like this:

let array = ['a', 'b', 'c']

Now I want to rearrange this to

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

Is there a built-in higher-order function to do that in JavaScript? Something like

let reordered = array.reorderMagic([1, 0, 0, 2, 0])

Where I could just specify an index array? If not, can you suggest a library that can help me do these kinds of matrix-like manipulations?

like image 768
LeafLover Avatar asked Dec 08 '25 18:12

LeafLover


1 Answers

You can create a method on Array.prototype though It is not recommended

Read: JavaScript: What dangers are in extending Array.prototype?

if (!('reorderMagic' in Array.prototype)) {
  Array.prototype.reorderMagic = function(ref) {
    const arr = this;
    return ref.map((n) => arr[n]);
  };
}

let array = ["a", "b", "c"];
let reordered = array.reorderMagic([1, 0, 0, 2, 0]);
console.log(reordered);

But I won't recommend that because there might be a scenario where someone or any library might override your method(This is just one scenario)

So you can just make a utility function and get the desired result as:

function reorderMagic(arr, ref) {
  return ref.map((n) => arr[n]);
}

let array = ["a", "b", "c"];
let reordered = reorderMagic(array, [1, 0, 0, 2, 0]);
console.log(reordered);
like image 111
decpk Avatar answered Dec 11 '25 10:12

decpk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!