简体   繁体   中英

How can i map an array starting from the end of the array to the beginning?

I want to map an Array but I don't want to start the iteration from the beginning index. I want to start mapping the Array from the last index of the array and go all the way to the beginning descending.

How can I do this in JavaScript? Is there an easy way that JS provides or something I missed?

You just use the.reverse() method before mapping. Here is an example:

const array = ["one", "two", "three"];

const reversedMap = [...array].reverse().map(x => {
  return x;
});

This will return ["three", "two", "one"]

You can of course map it however u want, if you for example wanted an unordered list you would do something like this:

const array = ["one", "two", "three"];

const reversed = [...array].reverse().map(x => {
  return (
    <div>
      <ul>
        <li>{x}</li>
      </ul>
    </div>
  );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM