Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Map Array Last Item

I have this:

map = ranks.map((row, r) => (   row.map((rank, i) => {     return [element(r, i, state, rank, toggled, onClick)];   }) )); 

It maps through a 2-dimentional array. After each row, I'd like to insert <div class="clearfix"></div>.

I think, if I could somehow get the last index for each row, so I will be able to use it in the row map callback. Can someone show me how to do it?

like image 904
cocacrave Avatar asked Jul 04 '16 02:07

cocacrave


People also ask

How do you find the last element of an array on a map?

index ### returns the index(location of item in an array) of the current element. array. length - 1 ### gives us the length of the array and - 1 gives us the index of the last element in the array.

How do you select the last element of an array?

To get the last item without knowing beforehand how many items it contains, you can use the length property to determine it, and since the array count starts at 0, you can pick the last item by referencing the <array>. length - 1 item.

How will you change the last element of an array JavaScript?

Use the array. prototype. splice() to Remove the Last Element From an Array JavaScript. The splice() method is used to change the array by removing or replacing the elements.

What is map in JavaScript with example?

Definition and Usage. map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.


1 Answers

Try something like:

row.map((rank, i, row) => {   if (i + 1 === row.length) {     // Last one.   } else {     // Not last one.   } }) 

Old answer:

const rowLen = row.length; row.map((rank, i) => {   if (rowLen === i + 1) {     // last one   } else {     // not last one   } }) 
like image 55
LeoYuan 袁力皓 Avatar answered Sep 19 '22 18:09

LeoYuan 袁力皓