简体   繁体   中英

How can I pass the index from the filter function into the map function?

How can I pass the index from the filter function into the map function? Note: if I add index as a parameter from the map function it is not the index in the original array, but of the filter items only.

{itemArray.filter((item, index) => item.type === compItem.type)
  .map((item) => {
    return (
      <Row>
        <Col key={item.name} onClick={(e) => openItemEdit(e, index, item)} >
          {item.name} 
        </Col>
      </Row>
    );
  })}

I am iterating over a set of keys surrounding this code to group the items into sublists. I have a workaround solution of saving the item before editing and then finding it in the original array after editing, but using the index should be a lot faster.

If you want to know the index that it had in the original, unfiltered array, then i think the simplest solution is dropping the use of .filter and using that original array directly, as follows:

{itemArray.map((item, index) => {
  if (item.type !== compItem.type) {
    return null;
  }
  return (
    <Row>
      <Col key={item.name} onClick={(e) => openItemEdit(e, index, item)}>
        {item.name}
      </Col>
    </Row>
  );
})}

You can map each object to a new object first, containing the original index.

{
    itemArray
        .map((item, index) => ({ ...item, index }))
        .filter(item => item.type === compItem.type)
        .map(({ index, ...item }) => (
            <Row>
                <Col key={item.name} onClick={(e) => openItemEdit(e, index, item)} >
                    {item.name}
                </Col>
            </Row>
        ))
}

A less functional approach would be to push the JSX to an array when the condition is fulfilled, instead of filtering.

{
    (() => {
        const jsx = [];
        itemArray.forEach((item, index) => {
            if (item.type === compItem.type) {
                jsx.push(
                    <Row>
                        <Col key={item.name} onClick={(e) => openItemEdit(e, index, item)} >
                            {item.name}
                        </Col>
                    </Row>
                );
            }
        });
        return jsx;
    })()
}

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