Remove items from one array if not in the second array

两盒软妹~` 提交于 2019-12-01 20:17:21

You can make use of Array.prototype.filter and Array.prototype.concat to simply it:

arr_A = ["a","b","d","f","g"]
arr_B = ["a","g","k"]
arr_C = ["h"]

function getCommonItems(arrayA, arrayB, result) {
 result = result || [];
 result = result.concat(arrayA.filter(function(item) {
            return arrayB.indexOf(item) >= 0;    
          }));
 return result.sort();
}

alert(getCommonItems(arr_A, arr_B, arr_C).join(", "));
alert(getCommonItems(arr_B, arr_A, arr_C).join(", "));

For the first scenario:

arr_A = ["a","b","d","f","g"]
arr_B = ["a","c","f","h"]

function getDifference(arrayA, arrayB, result) {
 return arrayB.filter(function(item) {
            return arrayA.indexOf(item) === -1;    
  }).sort();
}

alert(getDifference(arr_A, arr_B).join(", "));
alert(getDifference(arr_B, arr_A).join(", "));

Do it like this:

//the array which will loose some items
var ar1 = ["a", "b", "c"];
//the array which is the template
var ar2 = ["d", "a", "b"];

var tmpar = [];

for(var i = 0; i < ar1.length; i++){
  if(ar2.indexOf(ar1[i]) !== -1){
    tmpar.push(ar1[i]);
  }
}

ar1 = tmpar;

alert(ar1);

We create a temporary array to store the valid values.

We make sure that the index of the value from the first array is not "-1". If it's "-1" the index is not found and therefore the value is not valid! We store everything which is not "-1" (so we store every valid value).

Array.prototype.contains =  function ( object )
{
	var i = 0, n = this.length;
	
	for ( i = 0 ; i < n ; i++ )
	{
		if ( this[i] === object )
		{
			return true;
		}
	}
	
	return false;
}

Array.prototype.removeItem = function(value, global) {
	var idx;
	var  n = this.length;
	while ( n-- ) {
		if ( value instanceof RegExp && value.test ( this[n]) 
		|| this[n] === value ) {
			this.splice (n, 1 );
			if ( !global ) return this;
		}
	}
	return this;
};

arr_A = ["a","b","d","f","g"];
arr_B = ["a","c","f","h"];

var item
while ( item = arr_A.pop() ) {
	arr_B.contains ( item ) && arr_B.removeItem ( item  );
}

arr_B;

arr_A = ["a","b","d","f","g"];
arr_B = ["a","c","f","h"];
var newArr = [];
var item
while ( item = arr_B.shift() ) {
	arr_A.contains ( item ) && newArr[ newArr.length ] = item ;
}
newArr;// ["a", "f"];

Opsss .... I believed I had given the answer and closed this post ... sorry !!!

Despite all the checks I made, the failure of the mine as your script was caused by a stupid mistake ... the array arr_A passed to the function was a modified copy of the original array.

Thank you all for your concern and help. Sorry again ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!