Skip to content

Instantly share code, notes, and snippets.

@jondlove
Last active May 13, 2020 19:41
Show Gist options
  • Save jondlove/7ede2c32c8dc53867379d20466a59bb8 to your computer and use it in GitHub Desktop.
Save jondlove/7ede2c32c8dc53867379d20466a59bb8 to your computer and use it in GitHub Desktop.
Swizzle array function for Google Sheets
////
// Return an array of cells that match a reference string in the input_cell
// Example:
// W | 5
// X | 3
// Y | 6
// Z | 5
//
//
// SWIZZLE_ARRAY("WXX", A1:D2) will return [A2,B2,B2]
// Best used with SUM, e.g. =SUM(SWIZZLE_ARRAY(...))
//
// @param input_cell A cell containing a string of letters to lookup
// @param reference_array A 2D array, where the first column contains letters and
// the second column contains values
// @returns array or null
function SWIZZLE_ARRAY(input_cell, reference_array) {
// Do some initial validation
if (input_cell.map) {
throw("Input cell must be a single cell, not an array")
}
if (!reference_array.map) {
throw ("Reference_array is not a valid selection [should be a 2 column array]");
}
var swizzle = "";
var matching_cells = [];
var characters = input_cell.split("");
for (var i = 0; i < characters.length; i++) {
let char = characters[i];
for (var j = 0; j < reference_array.length; j++) {
// Compare this character with the first column of this array)
if (reference_array[j][0] == char) {
// It matches! Add the "value" cell (second column) to our matching cell list
matching_cells.push(reference_array[j][1])
}
}
}
if (matching_cells.length > 0) {
return matching_cells;
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment