1

javascript arrays are like below,

var course_ids = (1, 2, 3, 4);
var selected = (1, 3);

for (var x = 0; x < course_ids.length; x++) {
  if (selected.find(checkCourse)) {
    table_data += "<td>true</td>";
  } else {
    table_data += "<td>false</td>";
  }
}

$('#exam_tbl tr:last').append(table_data);

function checkCourse(course_id) {
  return course_id;
}

html table contain all course_ids as th in a table row. Then i want to load selected into next row. but if selected course is there i want to show true in td else want to show false. sample is like below.

 ---------------------------------
|   1   |   2   |   3   |   4   |   //th
----------------------------------
|true   |false  |true   |false  | //td
-----------------------------------

please help me to do this.

Bhuwan
  • 16,525
  • 5
  • 34
  • 57
tenten
  • 1,276
  • 2
  • 26
  • 54

3 Answers3

2

You can use map() and join() to create html string and includes() to check if element is included in another array.

var course_ids = [1, 2, 3, 4];
var selected = [1, 3];

$('<tr>').append(course_ids
  .map(id => `<th>${id}</th>`)
  .join(''))
  .appendTo($('thead'))
  
$('<tr>').append(course_ids
  .map(e => `<td>${selected.includes(e)}</td>`)
  .join(''))
  .appendTo($('tbody'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="exam_tb">
  <thead></thead>
  <tbody></tbody>
</table>

Or you could use reduce() method and return one object with thead and tbody strings.

var course_ids = [1, 2, 3, 4];
var selected = [1, 3];

var html = course_ids
  .reduce(function(r, e) {
    r.thead += `<th>${e}</th>`;
    r.tbody += `<td>${selected.includes(e)}</td>`;
    return r;
  }, {thead: '', tbody: ''});
  
$('<tr>').append(html.thead).appendTo($('thead'))
$('<tr>').append(html.tbody).appendTo($('tbody'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="exam_tb">
  <thead></thead>
  <tbody></tbody>
</table>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

course_ids variable must holds an array.

course_ids = [1,2,3,4];

As you wrote the course_ids has value 4.

This is called comma separated operator.

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

console.log((1,2,3,4))
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1
    var course_ids = [1, 2, 3, 4, 5];
    var selected = [1, 3, 4];
    var table_data = "";

    for (var x = 0; x < course_ids.length; x++) {
      if (selected.indexOf(course_ids[x]) != -1) {
        table_data += "<td>true</td>";
      } else {
        table_data += "<td>false</td>";
      }
    }

    console.log(table_data);

$('#exam_tbl tr:last').append(table_data);