In this article, we will continue discussing the "Correct Formula Approach" by implementing the LOOKUP function. This function is widely used in spreadsheet software, such as Microsoft Excel or Google Sheets, to search for a specific value in one column and return a corresponding value in another column.
LOOKUP Function: Overview
The LOOKUP function is used to search for a value in a one-dimensional array (row or column) and return a corresponding value in the same position from another one-dimensional array. The syntax of the LOOKUP function is:
LOOKUP(search_key, array, [result_array])
Arguments
- search_key: The value to search for in the array.
- array: The one-dimensional array where the search_key is located.
- result_array: (Optional) The one-dimensional array where the corresponding value will be returned. If omitted, the LOOKUP function uses the same array as the search_key.
LOOKUP Function Implementation
We will implement a simple version of the LOOKUP function using the following steps:
- Find the position of the search_key in the array.
- Return the value from the result_array in the same position as the search_key.
Code Example
function lookUp(searchKey, array, resultArray) {
// Find the position of the searchKey in the array
let index = array.indexOf(searchKey);
// Check if the searchKey is not found in the array
if (index === -1) {
return "Key not found";
}
// Return the corresponding value from the resultArray
return resultArray[index];
}
// Usage example
let searchKey = 3;
let array = [1, 2, 3, 4, 5];
let resultArray = ['a', 'b', 'c', 'd', 'e'];
console.log(lookUp(searchKey, array, resultArray)); // Output: c
The LOOKUP function is an essential tool in many spreadsheet applications. Implementing a custom version of this function can help you better understand how it works and enable you to customize it according to specific requirements.
References
- Type: Article
Title: "LOOKUP function"
Source: Office Support (Microsoft) - Type: Book
Title: "Excel 2019 Bible"
Author: John Walkenbach - Type: Online Resource
Title: "LOOKUP function"
Source: Google Sheets Help