Home > Mobile >  How to transform and reorder array in JavaScript?
How to transform and reorder array in JavaScript?

Time:11-09

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?

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can create a method on Array.prototype

Extending Array.prototype is considered bad practice, but the rest of the solution does work well.

I would recommend an API something like this instead:

function chooseIndices(arr, indexes) {
  return indexes.map(i => arr[i]);
}

And then use it as such:

let array = ["a", "b", "c"];
let reordered = chooseIndices(array, [1, 0, 0, 2, 0]);
// reordered === ['b', 'a', 'a', 'c', 'a']

Caution:

The function above doesn't account for invalid indices. For example, if you use the index 5 in the example above, you'll just get an undefined for it.

You can decide how you want to handle invalid indices. But one option would be to simply filter those out before using the index array.

CodePudding user response:

const arr = ['a','b','c'];
const order = [1, 0, 0, 2, 0];

const reorderMagic = (arr, indexes) => indexes.map((i) => arr[i]);

console.log(reorderMagic(arr, order));
// [ "b","a","a","c","a"]
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related