Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
                            console.log(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

like image 235
Gayan Kalanamith Avatar asked Mar 12 '23 14:03

Gayan Kalanamith


2 Answers

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>;
                });
like image 104
james emanon Avatar answered Apr 09 '23 21:04

james emanon


Map injects two more arguments you're not currently using. The full callback signature is (element, index, wholeArray). You can then call .length on the array and compare it to the current element index.

like image 39
probablyup Avatar answered Apr 09 '23 19:04

probablyup