Generic JavaScript Function to Find Indexes of Objects in an Array by Property and Value.
When working with arrays of objects, it’s common to filter objects based on a specific property and its value. This function supports both case-sensitive and case-insensitive matching, and works for both string and numeric property values.
Below is the detailed explanation, code snippet, and examples for using this utility function in your JavaScript or SuiteScript code.
/**
* Finds the indexes of objects in an array where a specific property matches a given value.
* Supports both case-sensitive and case-insensitive comparisons.
*
* @param {Array<Object>} array - The array of objects to search through.
* @param {string} propertyName - The name of the property to match.
* @param {string|number} propertyValue - The value to match against the specified property.
* @param {boolean} [caseSensitive=true] - Whether to perform a case-sensitive match. Defaults to true.
* @returns {Array<number>} - An array of indexes where the objects match the specified property and value.
*
* @example
* const data = [
* { name: 'Alice', age: 25 },
* { name: 'Bob', age: 30 },
* { name: 'alice', age: 25 }
* ];
*
* // Case-sensitive match
* findIndexesByProperty(data, 'name', 'Alice', true); // Returns: [0]
*
* // Case-insensitive match
* findIndexesByProperty(data, 'name', 'Alice', false); // Returns: [0, 2]
*
* // Numeric property match
* findIndexesByProperty(data, 'age', 25); // Returns: [0, 2]
*/
function findIndexesByProperty(array, propertyName, propertyValue, caseSensitive = true) {
// Ensure input array is valid
if (!Array.isArray(array)) {
throw new TypeError('The first parameter "array" must be an array.');
}
// Reduce function to collect matching indexes
const matchingIndexes = array.reduce((indexes, item, index) => {
// Ensure the item is an object
if (typeof item !== 'object' || item === null) {
return indexes;
}
// Get the value of the specified property
let itemValue = item[propertyName];
// Convert strings to lowercase for case-insensitive comparison
if (!caseSensitive && typeof itemValue === 'string' && typeof propertyValue === 'string') {
itemValue = itemValue.toLowerCase();
propertyValue = propertyValue.toLowerCase();
}
// Check for equality: strict for strings, loose for numbers
if (itemValue === propertyValue || (typeof itemValue === 'number' && itemValue == propertyValue)) {
indexes.push(index); // Add index to the results array
}
return indexes; // Return the updated list of indexes
}, []);
return matchingIndexes; // Return all matching indexes
}