Home:ALL Converter>How to filter array for only exact match in Google Apps Script/Javascript

How to filter array for only exact match in Google Apps Script/Javascript

Ask Time:2021-02-07T04:24:50         Author:Speckix

Json Formatter

I'm trying to use Google Apps Script to filter only exact matches. I've seen similar questions, but I can't seem to apply them to my situation.

On one sheet, I have a table of information which has the item name in column A, its' ingredient in column B, and its' quantity in column C. Column A contains items named Test and Test 2. When I filter for Test 2, I get results of both Test and Test 2. Here is the code I'm using:

var costSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Cost');
var ingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Recipe Ingredient');

// Create list of items to filter from the full list
var rows = costSheet.getLastRow();
var itemList = costSheet.getRange(2, 1, rows - 1).getValues();

// Convert itemList to array to be used in filter
itemList = itemList.join();

// Get full non-filtered data
var fullList = ingSheet.getRange('A2:C514').getValues();

// Apply filter criteria
function checkMatch(item) {
  return itemList.indexOf(item[0]) != -1;
}
filterList = fullList.filter(checkMatch);

// Clear target location, then place filtered data
costSheet.getRange('C2:E514').clearContent();
costSheet.getRange(2, 3, filterList.length, 3).setValues(filterList);

I don't have any trouble getting accurate results for multiple items from all three columns, and the only issue I have is when I try to filter an item that begins with the name of another item in the full list (e.g. filtering for Test 2 returns both Test and Test 2, when I want it to just return Test 2).

I am new to working with Google Apps Script/Javascript, hence the 'amateur' coding.

Author:Speckix,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/66081574/how-to-filter-array-for-only-exact-match-in-google-apps-script-javascript
yy