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 that aren't in the second array, but i'm stuck.
Given that I use the following javascript code (it works great) to remove the equal items between the two arrays :
function check_dupli(arr_A, arr_B) {
for(var i = arr_B.length - 1; i >= 0; i--) {
for(var j = 0; j < arr_A.length; j++) {
if(arr_B[i] === arr_A[j]) {
arr_B.splice(i, 1);
}
}
}
arr_B.sort();
}
arr_A = ["a","b","d","f","g"]
arr_B = ["a","c","f","h"]
check_dupli(arr_A, arr_B) --> arr_B = ["c","h"]
check_dupli(arr_B, arr_A) --> arr_B = ["b","d","g"]
I thought to modify it in order to ignore the items not that are not in both arrays, and to obtain what I want, but something is going wrong because I also get the unwanted data :
function get_dupli(arr_A, arr_B, arr_C) {
for(var e = arr_B.length - 1; e >= 0; e--) {
for(var k = 0; k < arr_A.length; k++) {
if(arr_B[e] === arr_A[k]) {
arr_C.push(arr_B[e]);
}
}
}
arr_C.sort();
}
arr_A = ["a","b","d","f","g"]
arr_B = ["a","g","k"]
arr_C = ["h"]
get_dupli(arr_A, arr_B, arr_C) --> arr_C = ["a","g","h","k"] instead of --> ["a","g","h"]
get_dupli(arr_B, arr_A, arr_C) --> arr_C = ["a","b","d","f","g","h"] instead of --> ["a","g","h"]
Where I'm wrong? There is another way in pure javascript to solve the problem?
Thanks in advance for any help.
You can make use of
Array.prototype.filter
andArray.prototype.concat
to simply it:For the first scenario:
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 ...
Do it like this:
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).