Asked • 05/06/19

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

1 Expert Answer

By:

Gabriel F. answered • 10/10/19

Tutor
5.0 (85)

Full Stack Javascript Engineer & Mentor

Gabriel F.

not sure why the code editor messed up the alignment
Report

10/10/19

Gabriel F.

Disregard this part of the text: " if the value is 0 you delete that property from the object." I simplified the code.
Report

10/10/19

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.