Home > other >  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?

Time:11-16

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.

CodePudding user response:

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>
  );
})}

CodePudding user response:

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;
    })()
}
  • Related