Home > Blockchain >  Return an array from jquery selector each function
Return an array from jquery selector each function

Time:10-01

I have a table where I fetch the values of columns 1st td and 9th tds of all rows

$("table tr").each(function() {
  return ($(this).find("td").eq(0).text()   " "   $(this).find("td").eq(8).text())
}).join("#")

I need to get the result in the form of array

as

["apple 20", "banana 30", "pears 30"].join("#")

and the expected result is

apple 20#banana 30#pears 30

How can I modify my iteration to return an array. I may then join with any characters I need.

CodePudding user response:

You can do it like this:

var result = $("table tr").map(function() {
  return ($(this).find("td").eq(0).text()   " "   $(this).find("td").eq(1).text())
}).get().join("#").

.each will not return the redirected result you want, it will return all the tr in your table

Demo

  • Related