To remove element from an array.

Ashutosh35
Kilo Contributor

Hello, 

I have two fields test1(reference -> user table) and test2(list -> user table). Whatever value is entered in test1, should be copied to test2. Condition is if the previous value of test1 is present in the test2 list, it should remove the value from test2 and keep the other values as it is and add the current value test2.

1. If test2 is nil, test1 value should be copied

2. If not, it should append the value in test2 if it is not present. If it is present then it should remove the previous (test1)value from test2. 

 

For this, I wrote a before business rule on test1which runs on the condition when test1 changes. 

The script I am using is as follow - 

 

function executeRule(current, previous /*null when async*/) {

if(current.u_test2.nil()){
current.u_test2 = current.u_test1;

}
else{
var prev = previous.u_test1;
var users = current.u_test2.split(',');
users.push(current.u_test1.toString());

var arrayUtil = new ArrayUtil();
var a1 = new Array(users);
var a2 = new Array(prev);

var newUsers = arrayUtil.diff(a1, a2);
current.u_test2 = newUsers.toString();
}

})(current, previous);

 

This script is appending to test2 but it is not removing the previous user from test2. 

 

Can someone please help here. I would really appreciate any help! 

 

1 ACCEPTED SOLUTION

Dylan Mann1
Giga Guru

You can simplify this whole thing by using indexOf() and splice(), see below:

var user = current.test1.toString();
var user_list = current.test2.split(",");

// User not present in list collector
if(user_list.indexOf(user) == -1) {
   user_list.push(user);
} else {
   user_list.splice(user_list.indexOf(user), 1); // Remove user from list
}

current.test2 = user_list;

View solution in original post

4 REPLIES 4

Dylan Mann1
Giga Guru

You can simplify this whole thing by using indexOf() and splice(), see below:

var user = current.test1.toString();
var user_list = current.test2.split(",");

// User not present in list collector
if(user_list.indexOf(user) == -1) {
   user_list.push(user);
} else {
   user_list.splice(user_list.indexOf(user), 1); // Remove user from list
}

current.test2 = user_list;

Thank you, Dylan. I tried the same but I am not getting the desired output. If I add an existing user here, I am getting output as shared in the screenshot. 

Do you have any idea what's going wrong?

find_real_file.png

You're welcome! I think all you need to do is return a string instead of an array so:

current.test2 = user_list.toString();

Community Alums
Not applicable

Hi , you can use this script 

 

var tab = ["A","B","C","D"];
var del = ["B","D"];
for(var i in del) 
tab.splice(tab.indexOf(del[i]), 1);
gs.print(tab); // output  A,C