我有一个二维JS数组,其中一些行是无用的,需要删除; 特别是我需要删除嵌入在其他行中的行(通过说行B嵌入行AI意味着不仅A是B的超集,而且A包含B中的所有元素,按顺序和相同的订单)
EX。我有:
var matrix = [
["User","Shop","Offer","Product","File"],
["User","Shop","File"],
["User","Shop","Map"],
["User","Shop","Promotion"],
["User","Shop","Offer","Product","Reservation"],
["User","Group","Accesslevel"],
["User","Group"],
["User","Reservation"],
["User","Shop"],
["User","Shop","Offer","Product","Markers"]
];
在此示例中,不应删除第二行([" User"," Shop"," File"])(其所有元素都在第一行,但不是连续的);
第7行(["用户","组"])应该被删除,因为它嵌入在第6行([" User"," Group"," Accesslevel"])以及第9行([" User"," Shop"])因为嵌入在许多其他人中..
我正在寻找一种可能有效的算法来检查一个阵列是否嵌入另一个阵列中; 我将在nodejs中使用它。
答案 0 :(得分:1)
这是我几天前用于同一目的的解决方案,但在客户端,这也适用于节点服务器。 http://jsfiddle.net/8wLst3qr/ 我已根据您的需要更改了程序,
我在这里做的是,
一些初始化,
var matrix = [
["User","Shop","Offer","Product","File"],
["User","Shop","File"],
["User","Shop","Map"],
["User","Shop","Promotion"],
["User","Shop","Offer","Product","Reservation"],
["User","Group","Accesslevel"],
["User","Group"],
["User","Reservation"],
["User","Shop"],
["User","Shop","Offer","Product","Markers"]
];
var tempArr=matrix;
这是步骤
- 将数组数组转换为字符串数组 - (这是因为只有当它们的顺序相同时才需要清除冗余数据),代码如下。
醇>
var json=[];
for(k=0;k<tempArr.length;k++)
{
json[k]=tempArr[k].toString();
}
- 然后匹配数组中其他字符串中每个字符串的索引,如果匹配,检查长度较小的字符串并删除 它。
醇>
for(k=0;k<json.length;k++)
{
for(l=0;l<json.length;l++)
{
console.log("val l="+json[l]+"val k="+json[k]+"value="+json[l].indexOf(json[k]));
console.log("k="+k+";l="+l);
if(k!=l && (json[k].indexOf(json[l]) !=-1))
{
console.log("removing");
console.log("removing");
if(json[k].length>json[l].length)
{
json.splice(l, 1);
}
else
{
json.splice(k, 1);
}
}
}
}
希望它有所帮助,
编辑 - 抱歉,您需要检查console.log以获取小提琴输出
答案 1 :(得分:1)
这应该可以解决问题。
// Is row2 "embedded" in row1?
function embedded(row1, row2) {
return row2.length < row1.length &&
row2.every(function(elt, i) { return elt === row1[i]; });
}
//filter out rows in matrix which are "embedded" in other rows
matrix.filter(function(row) {
return !matrix.some(function(row2) { return embedded(row2, row); });
});