js:如何从二维数组中过滤出重复项?

时间:2019-01-04 07:30:52

标签: javascript arrays repeat

有什么办法可以解决以下问题: 这是原始数据:

var m = [["a", "b"], ["c", "d", "e"], ["f", "g", "h"]]
var n = ["a","d","e", "h"]

我想获取数据:

[["a"], ["d","e"], ["h"]]

我尝试过:

function remove(arr, val) { 
    arr.forEach(v => {
        var index = v.indexOf(val); 
        if (index === -1) { 
            v.splice(index, 1);
        }
    });       
};
n.forEach(val=>{
    remove(m, val);
})
console.log(m)

但是我失败了。 有解决问题的方法吗?

3 个答案:

答案 0 :(得分:4)

如果可以使用新数组,则可以mapfilter m通过n中是否包含要迭代的项来实现:

var m = [["a", "b"], ["c", "d", "e"], ["f", "g", "h"]]
var n = ["a","d","e", "h"]

const filteredM = m.map(
  arr => arr.filter(
    item => n.includes(item)
  )
);
console.log(filteredM);

答案 1 :(得分:1)

您可以从数组末尾进行迭代,并拼接不常见的项目。

有必要从头开始,因为如果从头开始迭代,则拼接(在这种情况下)会更改数组的长度和实际索引。

var m = [["a", "b"], ["c", "d", "e"], ["f", "g", "h"]],
    n = ["a", "d", "e", "h"];

m.forEach(a => {
    var i = a.length;
    while (i--) {
        if (!n.includes(a[i])) {
            a.splice(i, 1);
        }
    }
});

console.log(m); // [["a"], ["d", "e"], ["h"]]
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

#Sign_up {
    opacity: 1;
    box-sizing: border-box;
    overflow: visible;
    white-space: nowrap;
    height: 50px;
    line-height: 50px;
    text-align: center;
    display: block;
}