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

前端 未结 8 923
终归单人心
终归单人心 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.

    0 讨论(0)
  • 2020-12-31 07:33

    If you just want to map a portion of an array, you should first filter() your array to obtain the expected portion according to conditions :

    array.filter(item => <condition>).map();
    
    0 讨论(0)
  • 2020-12-31 07:33

    There is no version of the map() function that only maps a partial of the array.

    You could use .map() in conjunction with .filter().

    You get the index of the current element as the second arg of map and if you have a variable for current page and page size you can quite easily filter the right page from your array without having to really slice it up.

    var currentPage = 1;
    var pageSize = 25;
    
    dataArray.filter(function(elt, index) {
    
        var upperThreshold = currentPage * pageSize;
        var lowerThreshold = currentPage * pageSize - pageSize;
    
        return index < upperThreshold && index > lowerThreshold;
    
    });
    
    0 讨论(0)
  • 2020-12-31 07:35

    Array#map iterates over all items.

    The map() method creates a new array with the results of calling a provided function on every element in this array.

    You could use Array#filter

    The filter() method creates a new array with all elements that pass the test implemented by the provided function.

    for the wanted items and then apply map for the wanted format.

    0 讨论(0)
  • 2020-12-31 07:36

    you could use the slice function before to map the array, it looks like you want to do some pagination there.

    var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
    var citrus = fruits.slice(1, 3);
    
    // fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
    // citrus contains ['Orange','Lemon']

    0 讨论(0)
  • 2020-12-31 07:38

    Do not try to solve this problem with a hack in your mapping step.

    Instead, slice() the list to the right length first before the mapping:

    class Feed extends React.Component {
      constructor(props) {
        super(props)
        
        this.handleShowMore = this.handleShowMore.bind(this)
        
        this.state = {
          items: ['Item A', 'Item B', 'Item C', 'Item D'],
          showItems: 2
        }
      }
      
      handleShowMore() {
        this.setState({
          showItems: 
            this.state.showItems >= this.state.items.length ?
              this.state.showItems : this.state.showItems + 1
        })
      }
      
      render() {
        const items = this.state.items.slice(0, this.state.showItems).map(
          (item) => <div>{item}</div>
        )
        
        return (
          <div>
            {items}
            <button onClick={this.handleShowMore}>
              Show more!
            </button>
          </div>
        )
      }
    }
      
    ReactDOM.render(
      <Feed />,
      document.getElementById('root')
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    
    <div id='root'></div>

    0 讨论(0)
提交回复
热议问题