我需要函数从数组a和b返回,包含b元素的新数组,在数组a中不存在。 例如:
a = [1,2,3,4]
b = [0,3,5]
return = [0, 5]
但元素是数组,例如:
a = [["a","fd","asfd"],["adsf","fdf","dsf"]
我尝试了很多,但没有任何反应。这是我的代码:
function clean(a, b){
var ln = a.toString()
for(var i = 0, length = b.length; i < length; i++) {
if(-1 !== ln.indexOf(String(b[i]))){
b.splice(ln.indexOf(b[i].toString()), 1)
}
}
return shorter;
}
它不起作用。
答案 0 :(得分:0)
试试这个 -
a = [1,2,3,4]
b = [0,3,5]
function clean(a, b){
var bb = b.slice(0); //making sure we are not changing the actual array
for(var i = 0; i < a.length; i++){
var index = bb.indexOf(a[i]);
if(index > -1){
bb.splice(index, 1);
}
}
return bb;
}
console.log(clean(a,b));
console.log(b);
输出:
[0, 5]
[0, 3, 5]
答案 1 :(得分:0)
我尝试了以下内容,但效果很好。
var b = [0,3,5];
var a = [1,2,3,4];
var ret = []
for(var i=0;i<b.length;i++){
var flag =0;
for(var j=0;j<a.length;j++){
if(a[j]===b[i]){
flag=1;
}
}
if(flag==0)
{
ret.push(b[i]);
}
}
console.log(ret);
答案 2 :(得分:0)
// The question has two parts:
// The second in order of the question is:
// Make a flat list from a two-dimensional array:
aFlat = [].concat.apply([],a);
// The first is: Get all elements from b
// that are not contained in a (resp. aFlat):
c = b.filter( function(element) { return aFlat.indexOf(element) == -1 });