Is it possible to map only a portion of an array? (Array.map())

前端 未结 8 957
终归单人心
终归单人心 2020-12-31 07:16

I am building a project using React.js as a front-end framework. On one particular page I am displaying a full data set to the user. I have an Array which contains this full

8条回答
  •  攒了一身酷
    2020-12-31 07:26

    Using slice() is better than adding a condition to your map or reduce function, but it still creates an additional, unused copy of that segment of the array. Depending on what you're doing, that might not be desired. Instead, just use a custom map function:

    function sliceMap(fn, from, toExclusive, array) {
      const len = toExclusive - from;
      const mapped = Array(len);
    
      for (let i = 0; i < len; i++) {
        mapped[i] = fn(array[i + from], i);
      }
    
      return mapped;
    };
    

    Note that fn receives the array value and the (now) zero-based index. You might want to pass the original index (i + from). You might also want to pass the full array as a third parameter, which is what Array.map does.

提交回复
热议问题