【问题标题】:Get the object array indexOf duplicate element in nodejs获取nodejs中的对象数组indexOf重复元素
【发布时间】:2017-05-31 04:01:42
【问题描述】:

我有一个大问题。我想 stackoverflow 成员可以帮助我。我在本地有一个 Excel 文件。而且我想阅读这个 Excel,如果 Excel 行有重复的数据而不是我写到控制台。

例如清楚;

这是我的 Excel 文件:

enter image description here

比我阅读的excel行代码:

workbook.xlsx.readFile('excelvalidation.xlsx').then(function() {
    var rowValues = {};
    var worksheet = workbook.getWorksheet(1);
    var columnCount = worksheet.columnCount;

    worksheet.eachRow(function(row, rowNumber) {
        if(rowNumber > 2) {
            var dizi = [];
            row.eachCell(function(cell, colNumber){
            dizi.push(cell.value);
        });

        rowValues[rowNumber-3] = dizi;
    }
});

for(var i = 0 ; i < Object.keys(rowValues).length ; i++) {
    console.log(" " + rowValues[i]);
}

rowValues 是所有行的对象。这意味着 1. row 是 rowValues 第一个元素和 2. row 是 rowValues 第二个元素 vs...

所以在 Excel 文件第 5 行和第 11 行重复,我想为消息“第 5 行和第 11 行重复”编写我想要的控制台。我该怎么做?感谢您的帮助..

【问题讨论】:

  • 那么您想要比较两个或多个单元格数组吗?

标签: arrays node.js excel duplicates


【解决方案1】:

您可以通过将数组中的值连接成单个字符串,然后使用 md5 函数来计算 rowValues 中每个项目的 md5 哈希值。 然后可以将此哈希用作具有这些值(导致该 md5 哈希的值)的行的索引。

这是一个可以检测多次出现(超过 2 个重复行)的示例实现:

var rowValues = [
  ['E', '10-15', 'ankara'],
  ['E', '10-15', 'antalya'],
  ['E', '20-25', 'ankara'],
  ['E', '20-25', 'antalya'],
  ['K', '10-15', 'ankara'],
  ['K', '10-15', 'antalya'],
  ['K', '20-25', 'ankara'],
  ['K', '20-25', 'antalya'],
  ['E', '20-25', 'ankara'],
  ['K', '10-15', 'antalya'],
  ['E', '20-25', 'ankara'],
];

var hashes = {};

rowValues.forEach(function(row, idx){
  var hash = md5(row.join('~~~'));
  if (hash in hashes) {
    hashes[hash].push(idx);
  } else {
    hashes[hash] = [idx];
  }
})

Object.keys(hashes).forEach(function(key, idx) {
  var msg = '';
  if (hashes[key].length > 1) {
    msg = 'Rows ' + hashes[key].join(' and ') + ' are duplicate\n';
    console.log(msg);
  }
});

在这里演示:https://jsfiddle.net/b5nqbavq/2/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-02
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    相关资源
    最近更新 更多