Question

Code Help: Two Lists - How to Add The Lists Together, How to Remove (Subtract) the lists?

  • 3 January 2023
  • 2 replies
  • 108 views

Userlevel 1
Badge

Hi,

 

I’m hoping someone can help me. I’ve been playing around to try and do this, to mixed results.

The input values are coming in via webhook, as a list comma separated list


Example 1: Adding 2 to 1

Input 1: [Alice, Bob]

Input 2: [Charlie]

Desired Output: [Alice, Bob, Charlie]

 

Example 2: Subtract 2 from 1

Input 1: [Alice, Bob, Charlie]

Input 2: [Bob]

Desired Output: [Alice, Charlie]

 

I’ve been playing around with code in both Javascript & Python to try and achieve these results.

I thought I had it, but instead of adding / subtract the items in the list, it seemed to add / delete the individual characters instead. But maybe I was outputting it wrong?

 

Thank you for any help you can offer.

 


This post has been closed for comments. Please create a new post if you need help or have a question about this topic.

2 replies

Userlevel 7
Badge +14

Hi @JayK 

Good question.

Check out this related Zapier Topic for Code Mode:

 

Userlevel 6
Badge +8

Hi @JayK!

For the first scenario, you can use the following Javascript code:

var array = ["Alice", "Bob"];
var itemsToAdd = ["Charlie"];

for (var i = 0; i < itemsToAdd.length; i++) {
array.push(itemsToAdd[i]);
}

array.sort(); // Assuming you always want the results in alphabetical order

output = [{array}];

And this for the second scenario:

var array = ["Alice", "Bob", "Charlie"];
var itemsToRemove = ["Sam"];

for (var i = 0; i < itemsToRemove.length; i++) {
if (array.indexOf(itemsToRemove[i]) !== -1) {
array.splice(array.indexOf(itemsToRemove[i]), 1);
}
}

output = [{array}];

Obviously, you want to replace the names with the actual values or use the .split() function on comma separated input data to create your arrays, but it sounds to me like you already got that far.

You’ll notice I named the variables “itemsToAdd” and “itemsToRemove” with a plural “items”. This is because you could add as many items to these arrays as you’d like, including 1 or even 0, and the loop will handle each of them one at a time. For example, you could have the following code and end up with an output of [Alice, Andrew, Zeke]:

var array = ["Alice", "Bob", "Charlie"];
var itemsToAdd = ["Andrew", "Sam", "Zeke"];
var itemsToRemove = ["Sam", "Bob", "Charlie", "Sally"];

// Note how Sally is listed as an item to remove, but is not included in the original array OR in the itemsToAdd variable...scenarios like this are what the if statement in the second for loop are set up to handle.

for (var i = 0; i < itemsToAdd.length; i++) {
array.push(itemsToAdd[i]);
}

for (var i = 0; i < itemsToRemove.length; i++) {
if (array.indexOf(itemsToRemove[i]) !== -1) {
array.splice(array.indexOf(itemsToRemove[i]), 1);
}
}

array.sort(); // Assuming you always want the results in alphabetical order

output = [{array}];