Search code examples
javascriptarraysreverse

Fastest way to call .map on reversed array JavaScript


Basically what title says: I want to be able to call .map on a reversed array, but I'm afraid that it would be too slow since I have to do this operation numerous times.

I know that the following method works:

let arr  = [1, 2, 3, 4, 5];
let rev_wrapped = arr.slice(0).reverse().map(item => `wrapped: ${item}`);

where rev_wrapped turns out to be:

[
  'wrapped: 5',
  'wrapped: 4',
  'wrapped: 3',
  'wrapped: 2',
  'wrapped: 1'
]

I was wondering if there is any faster way to do this, since .reverse() reverses the array entirely, while I just need to read data in reverse order.

In case this isn't possible, I would also be ok with a data structure which allows me to insert elements at the start without too much computational cost (since something like arr.splice(0,0,new_item) would rearrange the array completely at every insertions).


Solution

  • Inspired by the other answers, I just ended up doing something like:

    let arr  = [1, 2, 3, 4, 5];
    let wrapped = arr.map((_, i) => `wrapped ${arr[arr.length - 1 - i]}`);
    
    console.log(wrapped);

    If you are looking for a simple for implementation, check T.J. Crowder's answer, if you want a less compact and more explicit implementation, check Vivick's answer