首页 > 解决方案 > 在javascript中删除重复的数组数组

问题描述

我想对数组数组进行重复数据删除。重复数组是匹配元素索引子集的数组。在这种情况下,比如说 index[1]和 index [3]

const unDeduplicated = [
  [ 11, 12, 13, 14, 15, ],
  [ 21, 22, 23, 24, 25, ],
  [ 31, 88, 33, 99, 35, ], // duplicate in indices: 1, 3 with row index 4
  [ 41, 42, 43, 44, 45, ],
  [ 51, 88, 53, 99, 55, ], // duplicate in indices: 1, 3 // delete this row from result
];

const deduplicated = getDeduplicated( unDeduplicated, [ 1, 3, ], );

console.log( deduplicated );
// expected result:
// [
//   [ 11, 12, 13, 14, 15, ],
//   [ 21, 22, 23, 24, 25, ],
//   [ 31, 88, 33, 99, 35, ],
//   [ 41, 42, 43, 44, 45, ],
//   // this row was omitted from result because it was duplicated at indices 1 and 3 with row index 2
// ]

什么功能getDeduplicated()可以给我这样的结果?

我已经尝试了以下功能,但这只是一个开始。它离给我想要的结果还差得远。但它让我知道我正在尝试做什么。

/**
 * Returns deduplicated array as a data grid ([][] -> 2D array)
 * @param { [][] } unDedupedDataGrid The original data grid to be deduplicated to include only unque rows as defined by the indices2compare.
 * @param { Number[] } indices2compare An array of indices to compare for each array element.
 * If every element at each index for a given row is duplicated elsewhere in the array,
 * then the array element is considered a duplicate
 * @returns { [][] }
 */
const getDeduplicated = ( unDedupedDataGrid, indices2compare, ) => {
  let deduped = [];
  unDedupedDataGrid.forEach( row => {
    const matchedArray = a.filter( row => row[1] === 88 && row[3] === 99 );
    const matchedArrayLength = matchedArray.length;
    if( matchedArrayLength ) return;
    deduped.push( row, );
  });
}

我研究了一些可能会有所帮助的 lodash 函数,_.filter_.some到目前为止,我似乎无法找到产生所需结果的结构。

标签: javascriptarraysduplicateslodash

解决方案


您可以在迭代行时根据列中的值创建Set 。您可以选择仅为指定列创建集合,例如在您的情况下为 1 和 3。然后,在遍历每一行时,检查该行中的任何指定列是否具有已经在相应集合中的值,如果存在,则丢弃该行。

(在手机上,无法输入实际代码。我猜代码也很简单)


推荐阅读