Kalanamith Kalanamith - 2 months ago 7x
HTML Question

JavaScript array map function how to determine the length and the index of current item

I have a js snippet which generate a table row with

td s as follows

var cols = this.props.cols;
data = this.state.data

return data.map(function (item) {
var cells = cols.map(function (colData) {
return <td>{item[colData.key]}</td>;

return <tr key={item.Id }>{cells}</tr>;

I want to determine the last column and want to add a button that particular td
How to get the length of cells inside the cols.map(function(coldata). um not sure whether ill be able to accomplish it by this approach


something like this would work. As yaycmyk mentioned your map function can take 3 args..

 1. the iterated item
 2. the index of the item
 3. the array that is being iterated on.

I just just compare the index to the length - 1

                return data.map(function (item) {
                    var cells = cols.map(function (colData, idx, arr) {
                         return (idx === arr.length -1)
                               ? <td><button /></td>
                               : <td>{item[colData.key]}</td>;

                    return <tr key={item.Id }>{cells}</tr>;