Removing items from an array

Hey all,
I'm hoping to hit an existing array with another array to remove the specific items from the original.
Like if I have [22, 33, 44, 55], and I hit it with a payload of [33, 44], I wind up with [22, 55] coming out. I've been looking at the javascript tutorials that were recommended on other posts looking for something similar, and I feel like I could get something going, but in a very round-about way. I get a feeling there's a more simple solution that I'm overlooking.

What I'm wanting to do is build an array using .push() and have the items populate in the dashboard dropdown node. Later I'd like to be able to remove items from that dropdown by checking the boxes on those items. I've got the first part working fine, the but removal seems to be less clear.

look at array.filter

e.g.

var itemToRemove = msg.removeItem;
var array = msg.payload; //assuming payload is an array!
msg.payload = array.filter(e => e != itemToRemove); 
return msg;

or if it is an array of items to remove...

var itemsToRemove = msg.removeItems;
var array = msg.payload; //assuming payload is an array!
msg.payload = array.filter(e => itemsToRemove.includes(e) == false ); 
return msg;

Always worth testing in a node shell...
image

This seems to be doing the trick. At least it gives me something to noodle around with. Thank you very much for the lightning fast response.

Here is something else to think about -- a change node using a JSONata expression that returns only items in the msg.original array that are not included in the msg.payload array:

image

Of course, if your original array is not inside the msg (i.e. in some context variable), the syntax would change a bit -- but the concept is the same... the expression inside square brackets is applied to each element in the outer array, and only those matching are returned.

5 Likes

Oh my...that Jsonata really is pretty. I should splash around in those waters a bit more.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.