Tuzi
Tuzi

Reputation: 160

How to display items of array from last to first item?

I have an array with items. I want to render all items in reverse, without changing the order of the array.

var array = [2,5,3,5,8,4,1];
array.map(item => {
return(<div>{item}</div>)    
})

//this will display: 2 5 3 5 8 4 1  
//but i want to display: 1 4 8 5 3 5 2

To be clear, I dont want to reverse the actual array because I need to be able to add new values into the array. All I want is to map the array in reverse.

Upvotes: 0

Views: 1815

Answers (2)

timnavigate
timnavigate

Reputation: 739

You can try a solution without explicitly using reverse:

var array = [2,5,3,5,8,4,1];

var arrayOutput = array.map((valye, index, inputArray) => inputArray[(inputArray.length - 1) - index]);

console.log(arrayOutput);

But, for a better understanding of basic loop mechanics, you can try the following constructions:

/* your array */
var array = [2, 5, 3, 5, 8, 4, 1];

/* loop forward from 2 to 1, 
 * when 'l = array.length' is number of array elements */
for (let i = 0, l = array.length; i < l; i++)
{
  console.log(array[i]);
}

/* your array */
var array = [2, 5, 3, 5, 8, 4, 1];

/* loop backward from 1 to 2, 
 * when 'array.length-1' is last element of array */
for (let i = array.length - 1; i >= 0; i--) 
{
  console.log(array[i]);
}

Upvotes: 0

Noah Gwynn
Noah Gwynn

Reputation: 256

You can do this method before you map...

let reverse = [...arr].reverse()

or even better...

[...array].reverse().map(item => {
    return(<div>{item}</div>)    
})

Upvotes: 3

Related Questions