【问题标题】:Is there a way to use map() on an array in reverse order with javascript?有没有办法在数组上使用 javascript 以相反的顺序使用 map()?
【发布时间】:2016-07-24 18:38:38
【问题描述】:

我想在 javascript 数组上使用 map() 函数,但我希望它以相反的顺序运行。

原因是,我在 Meteor 项目中渲染堆叠的 React 组件,并希望首先渲染顶级元素,而其余的则加载下面的图像。

var myArray = ['a', 'b', 'c', 'd', 'e'];
myArray.map(function (el, index, coll) {
    console.log(el + " ")
});

打印出a b c d e,但我希望有一个mapReverse() 可以打印e d c b a

有什么建议吗?

【问题讨论】:

  • 你为什么不reverse数组?
  • 为了对元素进行排序,我通过数组索引设置了 z-index。我想我可以将 z-index 设置为负数。
  • 听起来不错。
  • 顺便说一句,您实际上是否在使用map 返回的数组?否则,你应该考虑forEach
  • 您可以在地图回调中访问反向元素:console.log(coll[coll.length - index - 1] + " ")

标签: javascript arrays


【解决方案1】:

如果您不想反转原始数组,您可以对其进行浅拷贝,然后映射反转数组,

myArray.slice(0).reverse().map(function(...

【讨论】:

  • 我最终只使用负索引来指定 z-index,但以我提出问题的方式,这是最正确的。
  • 为什么我们需要 .slice(0) ?为什么不是 myArray.reverse() 而不是 myArray.slice(0).reverse() ?看起来我的评论的答案在这里:stackoverflow.com/questions/5024085/…
  • Haradzieniec - 它与原始问题的框架细节相吻合,因为需要原始排序来设置 Z-index css 属性,但反向打印。
  • @FahdLihidheb reverse() 确实修改了原始数组。
  • 哦,是的,我的错。,Thnx @Ferus
【解决方案2】:

根本不改变数组,这是我想出的单线 O(n) 解决方案:

myArray.map((val, index, array) => array[array.length - 1 - index]);

【讨论】:

  • val 在这里没有使用,所以我认为这不是 OP 想要的吗? (这仍然是一个很好的解决方案)
  • 另外,map() 的第三个参数是数组本身
【解决方案3】:

您可以使用Array.prototype.reduceRight()

var myArray = ["a", "b", "c", "d", "e"];
var res = myArray.reduceRight(function (arr, last, index, coll) {
    console.log(last, index);
    return (arr = arr.concat(last))
}, []);
console.log(res, myArray)

【讨论】:

  • noice(如果您仍然希望执行归约) - MDN:reduceRight() 方法对累加器和数组的每个值(从右到左)应用一个函数来归约它是一个单一的值。
【解决方案4】:

带有命名回调函数

const items = [1, 2, 3]; 
const reversedItems = items.map(function iterateItems(item) {
  return item; // or any logic you want to perform
}).reverse();

简写(没有命名回调函数) - 箭头语法,ES6

const items = [1, 2, 3];
const reversedItems = items.map(item => item).reverse();

这是结果

【讨论】:

  • map 被用作浅拷贝
  • 这太棒了
【解决方案5】:

另一种解决方案可能是:

const reverseArray = (arr) => arr.map((_, idx, arr) => arr[arr.length - 1 - idx ]);

您基本上使用数组索引

【讨论】:

  • 这似乎是一种奇怪的方式,但是如果您想要访问除了元素之外的索引,并且不想做归约等,那么 reduceRight 方法也很奇怪. 就我而言,这是最干净的解决方案。
  • 如果您需要在地图内做进一步的工作,使用 arr[...] 不需要第二个副本或操作原始数组。忘记了第三个参数。我在寻找什么!
【解决方案6】:

我更喜欢将 mapReverse 函数编写一次,然后使用它。 这也不需要复制数组。

function mapReverse(array, fn) {
    return array.reduceRight(function (result, el) {
        result.push(fn(el));
        return result;
    }, []);
}

console.log(mapReverse([1, 2, 3], function (i) { return i; }))
// [ 3, 2, 1 ]
console.log(mapReverse([1, 2, 3], function (i) { return i * 2; }))
// [ 6, 4, 2 ]

【讨论】:

    【解决方案7】:

    你只需要在.map()之前添加.slice(0).reverse()

    students.slice(0).reverse().map(e => e.id)
    

    【讨论】:

      【解决方案8】:

      这是我的 TypeScript 解决方案,它既 O(n) 又比其他解决方案更有效,因为它可以防止两次遍历数组:

      function reverseMap<T, O>(arg: T[], fn: (a: T) => O) {
         return arg.map((_, i, arr) => fn(arr[arr.length - i - 1]))
      }
      

      在 JavaScript 中:

      const reverseMap = (arg, fn) => arg.map((_, i, arr) => fn(arr[arr.length - 1 - i]))
      
      // Or 
      
      function reverseMap(arg, fn) {
          return arg.map((_, i, arr) => fn(arr[arr.length - i - 1]))
      }
      

      【讨论】:

        【解决方案9】:
        function mapRevers(reverse) {
            let reversed = reverse.map( (num,index,reverse) => reverse[(reverse.length-1)-index] );
            return reversed;
        }
        
        console.log(mapRevers(myArray));
        

        I 您将数组传递给映射 Revers,并在函数中返回反转后的数组。在地图 cb 中,您只需从传递的数组中获取索引从 10(长度)计数到 1 的值

        【讨论】:

        • 书面解释这段代码的作用可能会有所帮助。
        【解决方案10】:

        我认为将reverse() 键放在map 之后可以工作。

        tbl_products
          .map((products) => (
            <div
              key={products.pro_id}
              class="my-1 px-1 w-full md:w-1/2 lg:my-4 lg:px-4 lg:w-1/4 transform transition duration-500 hover:scale-105"
            >
              <article class="overflow-hidden rounded-lg border shadow">
                <a href="#">
                  <img
                    alt="Placeholder"
                    class="block h-auto w-full px-5 pt-3"
                    src={products.product_img}
                  />
                </a>
              </article>
            </div>
          ))
          .reverse();
        

        就我而言,它正在工作

        【讨论】:

          【解决方案11】:

          你可以先做 myArray.reverse()。

          var myArray = ['a', 'b', 'c', 'd', 'e'];
          myArray.reverse().map(function (el, index, coll) {
              console.log(el + " ")
          });
          

          【讨论】:

          • 一般来说,这将是我的解决方案,但在我使用的设置中,我使用的顶部卡放置在最后一个索引处。我想只是一些更好的索引可以解决这个问题。
          • 请注意,这将在原地反转原始数组,这意味着它将破坏性地改变数组的顺序。
          【解决方案12】:

          var myArray = ['a', 'b', 'c', 'd', 'e'];
          var reverseArray = myArray.reverse()
          reverseArray.map(function (el, index, coll) {
              console.log(el + " ")
          });

          【讨论】:

          • reverse 也会原地反转myArray。作为(意外的)副作用,您的 myArray 在执行这些代码后会被反转。同样的问题类似于this answer
          【解决方案13】:

          一个老问题,但对于新观众来说,这是使用 map 反转数组的最佳方法

          var myArray = ['a', 'b', 'c', 'd', 'e'];
          [...myArray].map(() => myArray.pop());
          

          【讨论】:

          • 这会修改原始数组
          • 也许你的意思是:[...myArray].map((_, _, arr) =&gt; arr.pop()); ?
          猜你喜欢
          • 2019-06-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-27
          • 2019-09-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多