Help

How to filter query records inline?

Topic Labels: Automations
1089 1
cancel
Showing results for 
Search instead for 
Did you mean: 
sistemas_urbita
6 - Interface Innovator
6 - Interface Innovator
Hi, 
 
I have been trying to iterate only a few itens in a table, with no success. Apparently the filter() method does not work as expected in the example below. I would expect both codes worked the same, but they don't.
 

 

let table = base.getTable("My table");
let query = await table.selectRecordsAsync({fields: [ 'Total' ]});

console.log('TEST 1 - uses filter() ');
let query = await table.selectRecordsAsync({fields: [ 'Total' ]});
for (let record of query.records.filter((each) => { 0 == each.getCellValue('Total') } )) {
  console.log('Found a zero!');
}

console.log('TEST 2 - without filter() ');
for (let record of query.records) {
  if ( 0 == record.getCellValue('Total') ) console.log('Found a zero!');
}

 

 
My table has 4 records, with values 0, 1, 0, 0 for 'Total'. This is the output I get:
 

 

TEST 1 - uses filter()
TEST 2 - without filter()
Found a zero!
Found a zero!
Found a zero!

 

 
Any thoughts?
 
1 Reply 1

Your anonymous function in your inline filter is not returning any records. This is because the function does not return a value, so all records fail the test.

Let's look at your filter

query.records.filter((each) => { 0 == each.getCellValue('Total') } ))

 Notice that your filter function uses curly quotes for the code block of the function.  When you use curly braces to indicate the beginning and end of the code block, you must use a return statement to return a value.

 

query.records.filter((each) => { return 0 == each.getCellValue('Total') } ))

 


If the function is a one-liner, you can remove the curly braces and the result of the one-liner is returned.

 

query.records.filter((each) => 0 == each.getCellValue('Total') ))

 


On the other hand, using an inline filter makes the code harder to read. Why not do the filtering first and then loop.

let query = await table.selectRecordsAsync({fields: [ 'Total' ]});
let recordsWhereTotalIsZero = query.records.filter(record => 0 == record.getCellValue('Total'))
for (let record of recordsWhereTotalIsZero ) {
  console.log('Found a zero!');
}