Filter a Two-Dimensional Array Based on Elements from a Different Array

With two sets of numeric elements stored as 2D arrays, one representing a full list and the other a partial list, I am seeking a function that can return the full list minus the partial list.

  • The partialListArr may contain duplicates, while the fullListArr does not.
  • The output also needs to be a 2D list as it will be utilized in .setValues().
  • All values are numerical.

Here are the attempted solutions:

function myFunction() {
  var ss = SpreadsheetApp.getActive();
  var partialListArr = ss.getSheetByName('sheet 2').getRange(1,1,357,1).getValues();
  var fullListArr = ss.getSheetByName('sheet 1').getRange(1,1,942,1).getValues();

  var arr = fullListArr.filter(function(item){
    return partialListArr.indexOf(item.id) === -1;
  }); 

  Logger.log(arr.length)
  Logger.log(arr)
}

At this point, the function accurately obtains the full list.

Another approach was tried with the following code:

function myFunction2(){
  var ss = SpreadsheetApp.getActive();
  var partialListArr = ss.getSheetByName('sheet 2').getRange(1,1,357,1).getValues();
  var fullListArr = ss.getSheetByName('sheet 1').getRange(1,1,942,1).getValues();

  var arr = fullListArr.map(function(e){return e[0];})
    .filter(function(e,i,a){return (a.indexOf(e)==i && partialListArr.indexOf(e) ==-1); })  

  Logger.log(arr.length)
  Logger.log(arr)
} 

However, this method falls short by returning only a portion of the expected results. Considering a scenario where fullListArr contains 943 values and partialListArr has 288 unique values, the anticipated result should be 655 values in arr, yet the actual output is 895, failing to return it as a 2D array.

For further clarification and to view code snippets, refer to the associated spreadsheet.

Efforts: The initial step involved flattening the lists when using the first function.

  var ss = SpreadsheetApp.getActive();
  var partialListArr = ss.getSheetByName('sheet 2').getRange(1,1,357,1).getValues();
  var fullListArr = ss.getSheetByName('sheet 1').getRange(1,1,942,1).getValues();

  var flatPartialListArr = [].concat.apply([], partialListArr);
  var flatFullListArr = [].concat.apply([], fullListArr);

  var arr = flatFullListArr.filter(function(item){
    return flatPartialListArr.indexOf(item) === -1;
  }); 

  Logger.log(arr.length)
  Logger.log(arr)

This modification resulted in the proper count for arr. The subsequent step involved transforming the output back into a 2D array for compatibility with .setValues. Below is the comprehensive function with the complete solution.

function myFunction() {
  var ss = SpreadsheetApp.getActive();
  var partialListArr = ss.getSheetByName('sheet 2').getRange(1,1,357,1).getValues();
  var fullListArr = ss.getSheetByName('sheet 1').getRange(1,1,942,1).getValues();

  var flatPartialListArr = [].concat.apply([], partialListArr);
  var flatFullListArr = [].concat.apply([], fullListArr);

  var flatArr = flatFullListArr.filter(function(item){
    return flatPartialListArr.indexOf(item) === -1;
  }); 

  //Convert to 2D again for input into .setValues
  var newArr = [];
  while(flatArr.length) newArr.push(flatArr.splice(0,1));

  Logger.log(newArr.length)
  Logger.log(newArr)

  return newArr;
}

Many thanks, Akrion!

Answer №1

Here is a snippet that may help with your issue:

const fullArray = [[1],[2],[3],[4],[5]]
const partialArray = [[3],[4]]

const filteredArray = fullArray.filter(item => !partialArray.find(p => p[0] === item[0]))
console.log(filteredArray)

The previous code snippet filters the array as needed. Your initial filter did not work because you did not consider the returned result, which is an array of arrays.

Therefore, in your specific case, you can try the following:

const updatedArray = fullListArray.filter(element => !partialListArray.find(p ==> p[0] === element[0]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to showcase information on the Angular frontend

When attempting to retrieve the Street name, I am seeing [object Object]. What is the optimal approach for displaying JSON data on the client side? I managed to display a street name but struggled with other components. How can I access the other elements ...

Is there a way to have a button function as a submit button for a form even when it is located in a separate component within a react application?

I am in the process of creating a user-friendly "My Account" page using react, where users can easily update their account information. I have divided my components into two sections: the navbar and the form itself. However, I am facing an issue with the s ...

Eliminate any additional spacing within the pre/code tags

I am currently utilizing prism.js for code highlighting. I have encountered an issue where there are unnecessary white spaces at the top and bottom of my output. You can view a live example here. <pre> <code class="language-css"> &lt ...

Are asynchronous promises thenable for chaining?

Can someone explain to me how asynchronous chaining works with thenable? I am new to using promises in Node.js and I am a bit confused about the concept. In the code example provided below, it seems like the promise returned from the previous Promise.the ...

How can I disable auto-fill for password input fields? Setting autocomplete="off" doesn't seem to be working

Hey there, I'm having some trouble with the autocomplete feature in Google Chrome. Can anyone suggest an alternative way to disable autocomplete for password fields? By the way, my project is using Vue.js. ...

Conceal or reveal form elements based on input selection

In my current HTML form generated by PHP, I have multiple instances of the following structure: function show(elem, show){ var elements = elem.parentNode.parentNode.parentNode.getElementsByClassName("hidden"); var i; for(i=0; i<eleme ...

Storing knockout view model data in a database and fetching it back

I am currently working on a web form that utilizes knockout, and I need to add a new feature that allows users to save the form as a draft in the database. Later on, they should be able to load it again to make modifications or submit it. Is there a built ...

Is it possible to transfer 2-dimensional arrays between functions in C?

I am currently working on a project that involves creating a grid with blank spaces and randomly placing 'x' characters within it. I have successfully achieved this, but I am now facing difficulty in creating a separate function to print out the ...

Loading external templates in Angular2 with Webpack2

Attempting to integrate ngtemplate-loader in a project using AngularJs 2 and Webpack 2 is proving challenging. While this setup has been successful in Angular 1.x projects with Webpack 1.x, it encounters an error when running in the browser: Uncaught Type ...

What is the best way to showcase search outcomes using ajax in a Django project?

In my current Django project, I am developing a feature that allows users to search for a name using a form. The view will then search for that name in the database after some transformation and display the results below the form. Currently, the entire pa ...

Uniquely tag an uploaded file

My code for uploading files is as follows: var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", uploadProgress, false); xhr.open("POST", requestUrl, true); xhr.send(f); I want to draw your attention to the fact that I have attached a l ...

Check if the content key Json exists by implementing Vue

Can anyone help me with checking the existence of "novalue"? For instance: { name: "maria", city_id: "novalue" .... } What would be the best way to do this in Vue? Should I use <div v-if="condition"> or a function? ...

Accessing the observable's value by subscribing to it

There is a defined observable called imageOptions$ in my code: imageOptions$: Observable<BoundImagesToProject[]> = this.imagesService .getBoundImages({ projectId: this.projectId }) .pipe(map((images) => (images.data))); and it is used in the temp ...

The href appending function will succeed in Ajax if the inArray method is used effectively

Once upon a time, I thought I had nailed it with my ajax login, but alas, I was mistaken. The ajax login feature was working like a charm, perfectly appending the username to a link. Everything was going smoothly until I wanted to implement a page refres ...

Creating interactive HTML buttons using JavaScript to trigger AJAX requests

My current task involves populating an HTML table to showcase users. By making API calls to retrieve user data, I utilize Javascript to add rows to the table. Each row ends with a delete button, intended to trigger a $put request to a separate API endpoint ...

Retrieve container for storing documents in JavaServer Pages

Previously, I created JSP and HTML code to upload a file from the hard disk into a database using <input type="file" name="upfile"> However, a dialog box with an "Open" button is displayed. What I am looking for is a "Save" button that will allow u ...

bootstrap navigation bar collapsible menu

Struggling with making the hamburger menu appear on my friend's site. Spent hours trying to troubleshoot, but still can't figure out why it's only showing up as a red box and appearing on larger screens instead of just smaller devices. Frust ...

The result of calling addEventListener is undefined

My issue lies with the addEventListener function, as it is not working correctly. I've created a function that requires an event listener to track scrolling and then execute a callback function. window.addEventListener("scroll", checkPosition); Unf ...

Utilize SoundCloud API to generate user profiles according to their unique identification within the system

In my system, I have implemented a process that takes an array of SoundCloud user IDs. These IDs are then iterated through a series of SC.get functions to gather information about each user, such as their user ID, username, followings, and genre preference ...

Learn how to dynamically activate an icon in Angular to enhance user interaction

HTML Code: The Zoom Component <div class="zoom py-3"> <i nz-icon nzType="minus" (click)="zoomToggle(false)" nzTheme="outline"></i><br> <i nz-icon nzType="plus" (click)=&q ...