Skip to content Skip to sidebar Skip to footer

Remove Items From One Array If Not In The Second Array

I state that I have tried for a long time before writing this post. For an InDesign script, I'm working with two array of ListItems. Now I'm trying to remove the items of one array

Solution 1:

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"]

functiongetCommonItems(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"]

functiongetDifference(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(", "));

Solution 2:

Do it like this:

//the array which will loose some itemsvar ar1 = ["a", "b", "c"];
//the array which is the templatevar 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).

Solution 3:

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

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

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;

Solution 4:

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"];

Solution 5:

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 ...

Post a Comment for "Remove Items From One Array If Not In The Second Array"