Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using filter instead of foreach

I am currently trying to execute some operations after retrieving some data, the format I am trying to achieve is an array of strings: let cleanedData = ['foo', 'bar']

The data I receive could either be an array of objects or an array of arrays that could have empty arrays that needs to be filtered out. So for example I can receive either: let notCleanedData = [['foo'],[],[],['bar']] or this let notCleanedData = [{var: 'foo'}, {var: 'bar'}]

This is my code, it is working but I would like to improve it in a cleaner way or with ES6+ methods I have tried to use a filter function without success, any advice?

function filterInputData(notCleanedData) {
  let cleanedInputData = [];
  notCleanedData.forEach(input => {
    if (input.length > 0) {
      cleanedInputData.push(input)
    }
    if (input.var) {
      cleanedInputData.push(input.var)
    }
  });
  return cleanedInputData;
}

console.log(
  filterInputData([['foo'],[],[],['bar']]) 
)  
console.log(
  filterInputData([{var: 'foo'}, {var: 'bar'}])
)  
like image 518
Filippo Rivolta Avatar asked Jun 16 '26 04:06

Filippo Rivolta


1 Answers

This is a simple one-line solution that comes to my mind without using any libraries:

const clean = (data) => data.map(item => item.var ||  item[0]).filter(item => item)

I tried it on the test inputs you provided:

const clean = (data) => data.map(item => item.var ||  item[0]).filter(item => item)

console.log(
  clean([['foo'],[],[],['bar']]) 
)  
console.log(
  clean([{var: 'foo'}, {var: 'bar'}])
)
like image 153
Mo Ganji Avatar answered Jun 18 '26 17:06

Mo Ganji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!