0

In the function below, I am trying to get the values of the imported_Id that are not present in the old_Id array, and store them them into a new array add_IDs. In the example below, I would want to store values 1004 and 1005 in a new array. I have tried using the filter() method and other variations of for loops but can't seem to get it right. Any suggestions on a solutions would be greatly appreciated!

function myfunction() {
 
 const old_id = ["1000","1001","1002","1003"];
 const imported_id = ["1000","1001","1002","1003","1004","1005"];
  
 const add_ids = [];
  
 
  for(var x = 0; x < imported_id.length; x++){
    const append_id = [];
     for(var y = 0; y < old_id.length; y++) {
       if (old_id[y].indexOf(imported_id[x]) == -1){
        append_id.push(imported_id[x]);

       }
     }
    add_ids.push(append_id[x]);
  }
 
  
  Logger.log(add_ids);
}
TheMaster
  • 45,448
  • 6
  • 62
  • 85
Alex
  • 37
  • 1
  • 8

2 Answers2

1

Use filter and array.includes() to check if the number is in the second array

const old_id = ["1000", "1001", "1002", "1003"];
const imported_id = ["1000", "1001", "1002", "1003", "1004", "1005"];
res = imported_id.filter((n) => !old_id.includes(n));
console.log(res);
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
1

When your script is modified, I would like to propose the following 2 patterns. In this case, both patterns are the same result.

Pattern 1:

In this pattern, your script is a bit modified.

Modification point:

  • In this case, I think that append_id can be used for checking the duplicate values.
    • For example, in this modification, when the duplicate values between old_id and imported_id are existing, the length of append_id is not 0. This is used.
  • By checking the length of append_id, the result value can be retrieved.

Modified script:

const old_id = ["1000","1001","1002","1003"];
const imported_id = ["1000","1001","1002","1003","1004","1005"];
const add_ids = [];
for (var x = 0; x < imported_id.length; x++) {
  const append_id = [];
  for (var y = 0; y < old_id.length; y++) {
    if (old_id[y].indexOf(imported_id[x]) != -1) {  // or  if (old_id[y] == imported_id[x]) {
      append_id.push(imported_id[x]);
    }
  }
  if (append_id.length == 0) {
    add_ids.push(imported_id[x]);
  }
}
console.log(add_ids);

Pattern 2:

In this pattern, "Array.prototype.indexOf()" is used instead of "String.prototype.indexOf()".

Modification point:

  • When you use indexOf, by using "Array.prototype.indexOf()" index of "String.prototype.indexOf()", I think that inner for loop is not required.

Modified script:

const old_id = ["1000","1001","1002","1003"];
const imported_id = ["1000","1001","1002","1003","1004","1005"];
const add_ids = [];
for (var x = 0; x < imported_id.length; x++) {
  if (old_id.indexOf(imported_id[x]) == -1) {
    add_ids.push(imported_id[x]);
  }
}
console.log(add_ids);

References:

Tanaike
  • 181,128
  • 11
  • 97
  • 165