如果存在于另一个多维数组中,如何从多维数组中删除该数组? [英] How to remove an array from a multidimensional array if it exists in another multidimensional array?

查看:60
本文介绍了如果存在于另一个多维数组中,如何从多维数组中删除该数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个多维数组,需要从数组A中删除存在于数组B中的所有数组。我没有运气就尝试过这种方法:

I have two multidimensional arrays and need to remove all the arrays from array A that exist in array B. I've tried it this way with no luck:

var arrayA = [[0,1], [2,0], [0,3], [4,0], [0,5]];

var arrayB = [[0,1], [0,3]];

arrayA = arrayA.filter( function( el ) {
  return arrayB.indexOf( el ) < 0;
} );

alert(arrayA);

当arrayA和arrayB中的元素是单个值,但它们是数组时,此方法有效。不确定我在做什么错吗?

This works when the elements in arrayA and arrayB are single values and but when they are arrays. Not sure what I am doing wrong?

推荐答案

Array.prototype.indexOf 使用严格等于比较来检查元素是否相等。由于 [] === []; 为假,因此这不适用于引用类型。您可以使用@tymeJV解决方案,该解决方案的复杂度 O(lenA * lenB)或预索引 arrayB $ c> O(lenA + lenB)

Array.prototype.indexOf uses strict equals comparison to check if elements are equal. This wont work for reference types since [] === []; is false. You can either use @tymeJV solution which is O(lenA*lenB) complexity or preindex arrayB making it O(lenA + lenB)

演示

function index(arr) {
    return arr.reduce(function(acc, item){
        return acc[JSON.stringify(item)] = item, acc
    }, {});    
}
var arrayA = [[0,1], [2,0], [0,3], [4,0], [0,5]];

var arrayB = [[0,1], [0,3]];

var indexB = index(arrayB);

arrayA = arrayA.filter( function( el ) {
  return !(JSON.stringify(el) in indexB);
} );

console.log(arrayA);

UPD
如果内部数组中元素的顺序为不隔离可以使用排序。这将使此任务 O(lenA * log(lenA)+ lenB * log(lenB))

< a href = http://jsfiddle.net/yznL15e9/1/ rel = nofollow>演示2 。

这篇关于如果存在于另一个多维数组中,如何从多维数组中删除该数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆