Using filter instead of foreach

reduce vs foreach performance
javascript map vs filter performance
difference between map and filter javascript
map vs foreach performance
javascript filter
javascript find vs filter performance
javascript foreach vs for performance
foreach javascript

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'}])
)  

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'}])
)

Why and when to use forEach, map, filter, reduce, and find in , This is a simple one-line solution that comes to my mind without using any libraries: const clean = (data) => data.map(item => item.var� Many posts discuss how to use .forEach(), .map(), .filter(), .reduce() and .find() on arrays in JavaScript. I thought it would be useful to provide an explanation of when to use the common array…

const input = [['foo'],[],[],['bar']]
const input2 = [{var: 'foo'}, {var: 'bar'}]

const clean = (data) => data && data[0].length // check type
    ? data.flat(1) // use new flat method if array
    : (data || []).map((e) => e.var) // map objects otherwise

Using filter instead of foreach, In the example below we would use .forEach() to iterate over an array of food and log that we would want to eat each of them. let food = ['mango� using filter() and forEach() instead of For Loops Hello, I wanted to rewrite the code using higher order functions and finally managed to do it. We need to use the Array.from method to transform the HTML collections ( li 's) into a real array before being able to apply the filter and forEach methods.

Here is a much cleaner approach using reduce:-

// This function assumes that the array inside the array has single value and the object inside array has only one key called var
function filterInputData(notCleanedData) {
    return notCleanedData.reduce((acc, item) => {
        if (item.length) acc.push(item[0]);
        if (item.var) acc.push(item.var);
        return acc;
    }, [])
}

Hope you find this useful.

forEach(), .map(), .filter() . What's the difference?, Reduce vs for loop vs foreach. // calculated the sum of Personally, I love map, reduce, filter, find and I am using them for a long time. They helped me write� The most common code review comments I give is, stop using forEach or _.each and start using specific methods like filter, map, reduce, some etc… it’s not just cleaner, it’s easy to

I'd bring in lodash to help here.

You can use flattenDeep to clean and flatten and map to test if the data includes objects.

Example:

function clean(data) {
   return 
     _.chain(data)
       .flattenDeep()
       .map(x => {
    	  if (x.var) {
            return x.var;
          }
      
          return x;
       })
      .value();
}

console.log(
  clean([['foo'],[],[],['bar']]) 
)  
console.log(
  clean([{var: 'foo'}, {var: 'bar'}])
) 
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Javascript performance test, What should I use if I want to have multiple filters, May be 1000 records to loop. The filter vs forEach thing is very very very low in the priority list for potential� Is't possible to use filter(),collect() and foreach() in single statement instead of multiple statements? I have a map and need to filter based on some condition and set some values to the content and return the map. My current looks like below, but i want all 3 in single statement. Map inputMap (contains all info)

In this situation you can use map to achieve what you want without foreach. Filter wont work since it can only remove elements from the list and not actually make any modifications to them.

function filterInputData(notCleanedData) {
    let cleanedInputData = notCleanedData.map((input) => {
        if (input.length > 0) {
            return input;
        }
        if (input.var) {
            return input.var;
        }
    }).filter(item => item !== undefined);
    return cleanedInputData;
}

ES6: Should I use filter or forEach? Whats the performance cost , Rather they both return a new array. They both accept a single parameter that is of type function. This function is then called on each item in the� If for some reason performance is really important for you at the clock cycle level, then use List<Item> instead of IList<Item>, so that the compiler can make use of direct (and inlinable) calls instead of virtual calls, and so that the iterator of List<T>, which is actually a struct, does not have to be boxed. But that's really trifling stuff.

Why you should replace forEach with map and filter in JavaScript , javascript map foreach example difference between foreach and map and filter javascript map performance reduce vs for loop. I have gone through the map and � Using the filter will ensure that all air particles are filtered out effectively while the fabric makes sure that there is no breathing in of the filter materials. The best type of filter

Difference between map, filter vs for and forEach and what would be , I did a simple test with an array of object and doing some operation via for loop/ foreach / javascript functions and observing the time it take to� The foreach statement is known to be a quicker alternative than using the ForEach-Object cmdlet. The ForEach-Object CmdLet If foreach is a statement and can only be used in a single way, ForEach-Object is a cmdlet with parameters that can be employed in a lot of different ways.

How To Use map(), filter(), and reduce() in JavaScript, Instead of the above, where we manually index into strings , we can call forEach , and receive the next string on every iteration. The updated�

Comments
  • Code Review is a more appropriate place to ask for improvements to working code.
  • I am not sure this is exactly working as intended. When I ran this with the array version of the data, I got "[ [ 'foo' ], [ 'bar' ] ]", not "[ 'foo', 'bar' ]". Would that then make this the right place to ask?
  • So smooth, thanks, I came up with the same solution but more verbose. Does item=>item filter empty items, right?
  • @FilippoRivolta yes it filters out the undefined items from empty arrays.
  • What does your notCleanedData look like? When I ran your answer with his input (notCleanedData = [['foo'],[],[],['bar']]), I got: [ [ 'foo' ], undefined, undefined, [ 'bar' ] ]
  • Ah my bad, didn't notice that not adding the item was an option. I've updated my answer.