Using map to iterate through two arrays

后端 未结 4 1877
日久生厌
日久生厌 2021-01-07 06:07

Currently in React, I am using array.map(function(text,index){}) to iterate through an array. But, how am I going to iterate through two arrays simultaneously u

相关标签:
4条回答
  • If at all possible, I would recommend storing the text alongside the images in an array of objects, eg:

    const objects = [{text: 'abc', image: '/img.png' }, /* others */];
    

    that way you can just iterate through the array and select both members at the same time, for example:

    objects.map(item => (<Component icon={item.image} text={item.text} />) )
    

    If this isn't possible then just map over one array and access the second array's members via the current index:

    sentences.map((text, index) => {
        const image = images[index];
        return (<Component icon={image} text={text} />);
    });
    
    0 讨论(0)
  • 2021-01-07 06:48

    Are the both arrays of same length? You can do something like below if your intention is to combine both in some way.

    array.map(function(text,index){
       return text + ' ' + array2[index]
    })
    

    In your case:

    var sentenceList = sentences.map(function(text,index){
                return <ListGroupItem key={index}>{text} <img src={icons[index]} /i> </ListGroupItem>;
            })
    return (
         <div>
           <ListGroup>
            {sentenceList}
          </ListGrouup>
       </div>
    );
    

    Notice, How Icon src is being assigned. The idea is that access icons array with the same index to get a corresponding icon.

    0 讨论(0)
  • 2021-01-07 06:59

    Generally, what you're looking for is a zip function, such as the one that lodash provides. Much like a real zipper, it combines two things of the same length into one:

    const zipped = _.zip(sentences, icons);
    
    return (
      <div>
        <ListGroup>
          {zipped.map(([sentence, icon], index) => (
            <ListGroupItem key={index}><Icon icon={icon} /> {text}</ListGroupItem>;
          ))}
        </ListGroup>
     </div>
    );
    

    Note, this is doing more iterations than are technically needed. If performance is an issue, you may want a solution that's a bit smart (not really in scope for your question though).

    0 讨论(0)
  • 2021-01-07 07:01

    You can't do this with built-in Array.prototype methods, but you can use something like this:

    function map2(arr1, arr2, func) {
        return arr1.map(
            (el, i) => { return func(el, arr2[i]); }
        );
    }
    

    (Of course, arr1 and arr2 are expected to have the same length)

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