Find Index in JavaScript
Although it seems like a find function which finds the position of an occurance is always good enough for searching, a findIndex can sometimes be more useful. For example, if a user is inserting an array of information (batch insert), they should know which specific columns had errors:
function insertBatch(data, callback) { // Simulate an API call with some error returns setTimeout(function() { callback([ data[0], data[1], { error: 'Cannot insert with a negative quantity' }, { error: '"row-2" was already specified' }, data[4] ]); }, 500); } const formattedUserInput = [ { id: 'row-1', display: 'Test A' , quantity: 100 }, { id: 'row-2', display: 'Test B' , quantity: 50 }, { id: 'row-3', display: 'Test C' , quantity: -100 }, { id: 'row-2', display: 'Test D' , quantity: 100 }, { id: 'row-5', display: 'Test E' , quantity: 1 }, ]; insertBatch(formattedUserInput, function(data) { const errorIndex = findIndex(data, function(row) { return row.error !== undefined; }); if (errorIndex !== -1) { console.log('There was an error at row', (errorIndex + 1) + ':'); console.log(data[errorIndex].error); } else { console.log('All rows inserted successfully'); } }); // There was an error at row 3 // Cannot insert with a negative quantity
A findIndex function is present in many libraries like Lodash. Here is a simple implementation used above to give a better idea of what it does:
function findIndex(array, callback) { for (let index = 0; index < array.length; index += 1) { if (callback(array[index]) === true) { return index; } } return -1; }
Of course fixing 1 row at would be annoying for a user, so a findIndices function would be better. It just involves one small change:
function findIndices(array, callback) { const indices = []; for (let index = 0; index < array.length; index += 1) { if (callback(array[index]) === true) { indices.push(index); } } return indices; }
Unfortunately, I could not find any libraries with a findIndices function unlike findIndex, so a custom function does have to be used in real code. Here is the modified error printing which also only requires a slight change:
function findIndicesVersion() { console.log('\nFind Indices Version:'); insertBatch(formattedUserInput, function(data) { const errorIndices = findIndices(data, function(row) { return row.error !== undefined; }); if (errorIndices.length !== 0) { errorIndices.forEach(function(errorIndex) { console.log('There was an error at row', (errorIndex + 1) + ':'); console.log(data[errorIndex].error); }); } else { console.log('All rows inserted successfully.'); } }); } // There was an error at row 3: // Cannot insert with a negative quantity // There was an error at row 4: // "row-2" was already specified
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/findIndex.js







