How to display duplicate rows in same color using datatable

安稳与你 提交于 2020-12-15 07:11:10

问题


I am using DataTable plugin for show rows in table. I want to show duplicate rows in same color. How i can do this someone pls help me. In the below example Black Winters we have duplicate row. I want to show these type of duplicate rows in different colors. Like I have duplicate data Black Winters and Orange i want to show these both duplicate rows in different color combination eg.: Black Winters color will be red and Orange color will be like blue.

$(document).ready(function() {
  var data = [{
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$3,120"
    },
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,300"
    },
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,300"
    }
  ];
  $("#table1").DataTable({
    data: data,
    columns: [{
        data: 'name'
      },
      {
        data: 'position'
      },
      {
        data: 'salary'
      },
    ]
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
  <thead>
    <tr>
      <th>name</th>
      <th>position</th>
      <th>salary</th>
    </tr>
  </thead>
</table>

回答1:


You can make use of below code where you can prepare map of duplicate rows inside 'rowCallback' function and apply color to dupliate rows in applyDuplicateRowColor function once datatable draw get completed

I have used duplicateColor array to pick random color for same rows, you can edit it and add more colors. also using duplicateColorIndex to get next duplicate color for next duplicate data, please make sure you have enough color in the array otherwise it will show arrayindexoutofbound error.

$(document).ready(function() {
   var duplicateColor = ['red', 'blue', 'yellow', 'green'];
   var len = duplicateColor.length;
   var duplicateColorIndex = 0;
   var duplicateRowMap = {};
  
     $.fn.applyDuplicateRowColor = function() {
       $("#table1 tr").each(function(){
       var name = $(this).find('td:eq(0)').text();
       var value = duplicateRowMap[name];
       if(value!='x') {
         $(this).css('color', duplicateColor[value]);
       }
      });
      //reset variables
       duplicateColorIndex = 0;
       duplicateRowMap = {};
    };
  
   var data = [{
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$3,120"
    },
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,300"
    },
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,200"
    },
    {
      "name": "Oranges",
      "position": "Project Engineer",
      "salary": "$1,100"
    },
    {
      "name": "Oranges",
      "position": "Project Engineer",
      "salary": "$1,000"
    }
  ];
  $("#table1").DataTable({
    data: data,
    columns: [{
        data: 'name'
      },
      {
        data: 'position'
      },
      {
        data: 'salary'
      },
    ],
    "rowCallback": function( row, data ) {
     var name = duplicateRowMap[data.name];
     if(name) {
       if(name == 'X') {
         duplicateRowMap[data.name] = duplicateColorIndex;
         duplicateColorIndex++;
        if(duplicateColorIndex==len)
           duplicateColorIndex = 0;
       }
     } else {
       duplicateRowMap[data.name] = 'X';
     }
    },
    "fnDrawCallback": function( oSettings ) {
      $(this).applyDuplicateRowColor();
    }
  });
  //console.log(duplicateRowMap);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
  <thead>
    <tr>
      <th>name</th>
      <th>position</th>
      <th>salary</th>
    </tr>
  </thead>
</table>



回答2:


You can implement this using

  1. Using .map() method of array, in map method you just need to append new key with color value based on condition if duplicate row is count is greater then 1 then color will be orange otherwise 'red'.

  2. Now need to use createdRow() method for data table.

See below working code snippet

$(document).ready(function() {
  var data = [{
    "name": "Tiger Nixon",
    "position": "System Architect",
    "salary": "$3,120"
  }, {
    "name": "Black Winters",
    "position": "Project Engineer",
    "salary": "$1,300"
  }, {
    "name": "Black Winters",
    "position": "Project Engineer",
    "salary": "$1,300"
  }].map((o,i,arr)=>{
    o.color = arr.filter(({name})=>name===o.name).length>1 ?'orange':'red';
    return o;
  });
  

  $("#table1").DataTable({
    data: data,
    columns: [{
      data: 'name'
    }, {
      data: 'position'
    }, {
      data: 'salary'
    }],
    "createdRow": function(row, data, dataIndex) {
        $(row).css("background-color", data.color);
    },
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
  <thead>
    <tr>
      <th>name</th>
      <th>position</th>
      <th>salary</th>
    </tr>
  </thead>
</table>



回答3:


First you need to check which elements are duplicates and you need to manage it's status in other array. so in createdRow you can check for duplicate rows. Check on below link.

https://jsfiddle.net/t2cn571z/

Try below solution.

$(document).ready(function() {
  var data = [{
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$3,120"
    },
    {
      "name": "Orange",
      "position": "Developer",
      "salary": "$1,700"
    },
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,300"
    },
    
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,300"
    },
    
    {
      "name": "Orange",
      "position": "Developer",
      "salary": "$1,700"
    }
  ];
  
  //find duplicates values
  var array = [];
  data.forEach(myFunction)
  
  function myFunction(item, index) {
 
 if( array.length == 0)
 {
 array.push({"name":item.name,"isduplicate" : 0})
 }
 else
 {
 if (array.filter(e => e.name === item.name).length == 0) 
 /* vendors contains the element we're looking for */
 {
 array.push({"name":item.name,"isduplicate" : 0})
 }
 else
 {
 
 array = array.filter((e) => e.name !== item.name);
 
 array.push({"name":item.name,"isduplicate" : 1})
 }
 }
 
 }
  
  $("#table1").DataTable({
    data: data,
     "createdRow": function ( row, data, index ) {
    
     var dataValue = array.find(x => x.name === data.name);
            if ( dataValue.isduplicate == 1 ) {
               if(dataValue.name == 'Black Winters')
                $(row).css('color','red')
               else if(dataValue.name == 'Orange')
                $(row).css('color','blue')
               
            }
        },
    columns: [{
        data: 'name'
      },
      {
        data: 'position'
      },
      {
        data: 'salary'
      },
    ]
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
  <thead>
    <tr>
      <th>name</th>
      <th>position</th>
      <th>salary</th>
    </tr>
  </thead>
</table>



回答4:


A little bit messy but it does what you need mostly. For a unique color for each set of different data you would need to created a random color variable and put that on the row instead of a class like I did. This is not very extendable but if you know how many columns then this works fine.

Good luck.

$(document).ready(function() {
  var data = [{
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$3,120"
    },
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,300"
    },
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,300"
    }
  ];
  $("#table1").DataTable({
    data: data,
    columns: [{
        data: 'name'
      },
      {
        data: 'position'
      },
      {
        data: 'salary'
      },
    ]
  });
});

$(document).ready(function() {

  // Search the table for doubles.
  function SearchForDoubles() {

    var table = $("#table1 tbody tr");
    var counter1 = 0;
    var counter2 = 0;

    var tr_currentName = "";
    var tr_newName = "";

    var tr_currentPosition = "";
    var tr_newPosition = "";

    var tr_currentSalary = "";
    var tr_newSalary = "";

    table.each(function() {

      // set the current tr html data
      tr_currentName = $(this).find("td:nth-child(1)").html();
      tr_currentPosition = $(this).find("td:nth-child(2)").html();
      tr_currentSalary = $(this).find("td:nth-child(3)").html();

      table.each(function() {


        tr_newName = $(this).find("td:nth-child(1)").html();
        tr_newPosition = $(this).find("td:nth-child(2)").html();
        tr_newSalary = $(this).find("td:nth-child(3)").html();
        /*
                console.log(counter1 +"!="+counter2);
                console.log(tr_currentName +"=="+tr_newName);
                console.log(tr_currentPosition +"=="+tr_newPosition);
                console.log(tr_currentSalary +"=="+tr_newSalary);
                */
        // check if there is a match
        if (counter1 != counter2 &&
          tr_currentName == tr_newName &&
          tr_currentPosition == tr_newPosition &&
          tr_currentSalary == tr_newSalary
        ) {

          // highlight the row
          $(this).addClass("doubleRecord");

        }

        counter2++;

      });
      counter2 = 0;
      counter1++;

    });

  }

  SearchForDoubles();

});
.doubleRecord {
  color: orange;
  font-weight: 700;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<table id="table1" class="display">
  <thead>
    <tr>
      <th>name</th>
      <th>position</th>
      <th>salary</th>
    </tr>
  </thead>
</table>



回答5:


There is option createdRow on datatable. You may check condition inside that option and add desire CSS.

Update: createdRow with initComplete and some logic do this for dynamic data. I edit answer after comment.

$(document).ready(function() {
  var data = [{
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$1,120"
    },
    {
      "name": "Shree",
      "position": "System Architect",
      "salary": "$3,120"
    },
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,300"
    },
    {
      "name": "Black Winters",
      "position": "Project Engineer",
      "salary": "$1,300"
    }
  ];
  var names = [];
  var dupliacteName = [];

  $("#table1").DataTable({
    data: data,
    "createdRow": function(row, data, index) {
      let name = data.name;
      if (names.indexOf(name) > -1) {
        dupliacteName.push(name);
      }
      $(row).attr('data-val', name).css({
        "color": "orange"
      });
      names.push(name);
    },
    "initComplete": function(settings, json) {
      $.each(dupliacteName, function(index, name) {
        $("[data-val='" + name + "']").css({
          "color": "red"
        });
      });
    },
    columns: [{
        data: 'name'
      },
      {
        data: 'position'
      },
      {
        data: 'salary'
      },
    ]
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>

<table id="table1" class="display">
  <thead>
    <tr>
      <th>name</th>
      <th>position</th>
      <th>salary</th>
    </tr>
  </thead>
</table>


来源:https://stackoverflow.com/questions/58831225/how-to-display-duplicate-rows-in-same-color-using-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!