如何将DataTable所有行的r_name存入数组并实现重复校验?
Hey there! Let's sort out this duplicate check for your DataTable. Here's a practical, step-by-step implementation that fits right into your existing code:
First, assuming your DataTable initialization looks like this (matching the code you mentioned starting with var t = $('#datatables').DataTable()):
var t = $('#datatables').DataTable({ // Your existing configuration options (columns, etc.) go here });
When you're ready to add a new row, follow these steps to prevent duplicate r_name entries:
Fetch all existing
r_namevalues from the table
Use DataTable'srows().data()method to iterate over all rows and extract ther_namefield. Adjust the code based on whether your table uses object-based or array-based data:- For object-based data (each row is an object like
{ r_name: "Sample Name", ... }):var existingNames = t.rows().data().map(row => row.r_name).toArray(); - For array-based data (each row is an array like
["ID", "Sample Name", ...], wherer_nameis at index 1 for example):var existingNames = t.rows().data().map(row => row[1]).toArray();
- For object-based data (each row is an object like
Check against the new row's
r_name
Define your new row data, grab itsr_name, and check if it already exists in the table:// Example new row data (adjust to match your actual data structure) var newRowData = { r_name: "New Registered Name", // Add other row fields here }; // Extract the new r_name (use newRowData[1] for array-based data) var newName = newRowData.r_name; if (existingNames.includes(newName)) { // Trigger warning if duplicate is found alert("警告:该r_name已注册!"); // Optional: Replace alert with a polished modal (like Bootstrap Modal) for better UX } else { // Add the row only if no duplicate exists t.row.add(newRowData).draw(false); }
Key Tips for Edge Cases:
- Case Insensitivity: The
includes()method is case-sensitive. If you want to ignore case differences, convert all names to lowercase (or uppercase) before comparison:var existingNames = t.rows().data().map(row => row.r_name.toLowerCase()).toArray(); var newName = newRowData.r_name.toLowerCase(); - Performance for Large Tables: If your table has hundreds of rows, iterating over all rows every time can slow things down. Instead, maintain a
Setto track names for faster lookups:// Initialize the Set when creating the DataTable var nameSet = new Set(t.rows().data().map(row => row.r_name)); // When adding a new row: if (nameSet.has(newName)) { alert("警告:该r_name已注册!"); } else { t.row.add(newRowData).draw(false); nameSet.add(newName); // Update the Set with the new name } // Remember to remove names from the Set if you ever delete rows!
内容的提问来源于stack exchange,提问作者Engr. Arda

