Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditional response in a map chained to a filter that may return an empty array

I have filter and map function chained. I need to do something conditional on whether a filter returns an empty array or not. However the map function on the array does not seem to be invoked if the filter returns an empty array.

const letters = ["a", "b", "c"];
const numbers = [1, 2, 3]

function result (arr) {

arr.filter((x) => {return x === "a"}).map((y, i, arr) => {

if(arr.length === 0) {
return (document.getElementById("p").innerHTML = "empty")
} else {
return (document.getElementById("p").innerHTML = "found it")
}})
}

Is this expected or am I doing something wrong?

I was expecting the filter result to be passed to the map function, which can be used as the 3rd argument of the map function: map(item, index, array)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s a JSFiddle of the problem
https://jsfiddle.net/sub3z0xh/

>Solution :

You’re right about what’s happening. Array methods run once per element in the source array. If the source array is empty, it doesn’t run.

This isn’t new or working different with array methods vs a basic for loop. Example:

const arr = [];

for (let i = 0; i < arr.length; i++) {
  console.log(“this code never runs because there are no elements to loop”);
}

So maybe just store the result of the filter in a variable instead. Get rid of the chained map since it may not run. Check the size/contents of your filtered array, then do stuff with that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading