Using map to filter and return a new object in es6

Viewed 981

I have the following code:

      allDesignDocs.rows.forEach((row: any) => {
        if (!designDocsName.includes(row.id.replace("_design/", ""))) {
          toBeRemoved = [{ _id: row.id, _rev: row.value.rev, "_deleted": true }, ...toBeRemoved];
        }

      });

which works fine. However I would like to use an in place update approach. So I chose map rather than foreach:

  var test = allDesignDocs.rows.map((row: any) => {
    if (!designDocsName.includes(row.id.replace("_design/", ""))) {
      return { _id: row.id, _rev: row.value.rev, "_deleted": true };
    }

  });

So the above returns arrays including undefined when the condition is not happy. I just want the array to contains values returned from inside if and ignore all undefined. I know I can loop trhough the result and clean it but that is not a clean way. Is there any es6 function which can provide the above functionality?

2 Answers

Use filter() after map() to filter undefined values.

var test = allDesignDocs.rows.map((row: any) => {
   if (!designDocsName.includes(row.id.replace("_design/", ""))) {
     return { _id: row.id, _rev: row.value.rev, "_deleted": true };
   }
 }).filter(item => item !== undefined); // Can also use filter(item => item);

Or use reduce():

var test = allDesignDocs.rows.reduce((acc, row: any) => {
  if (!designDocsName.includes(row.id.replace("_design/", ""))) {
    acc.push({ _id: row.id, _rev: row.value.rev, "_deleted": true });
  }
  return acc;
}, []);

You can use .reduce

For instance:

[1,2,3,4].reduce((acc,n)=>{
    if (n % 2 == 0) {
        acc.push(n*4)
    }
    return acc;
},[])

Which would produce a list of even numbers * 4, alternatively combine .filter and .map.

Related