Friday, April 13, 2018

.some versus .find versus .filter versus .map in JavaScript

I found these starting to blur together some for me and so a cheatsheet is in order, right? Let's assume we have an array of cats in a variable called cats...

  1. .some will return a true or false value for if any one item in a collection meets a condition, say for example if any one of the cats has all nine lives left and you may put verbose rules in .some so while you are finding the first match and doing nothing with the Boolean being returned you could also trigger other methods or set some state somewhere
  2. .find will find the first match so we could find the first of the cats that still has nine lives
  3. .filter will create a new array from an array with only the items surviving the trip that match a condition so we could filter all of the cats from cats which have nine lives left into a fullyCharged array
  4. .map will allow us to transform every object in the array, turning cats into ostriches, while also filtering too if we like based on the conditions of our choosing (The rules inside of .map may be verbose and you could turn some of the cats into ostriches and some of the cats into walruses while having the ostriches and walruses end up sprinkled into the same collection together. Pragmatically, this sort of transformation would be better served by two separate mapping operations in which some filtering also occurs putting just the ostriches in one array and just the walruses in another array.)
  5. .forEach ...I don't really need to tell you what this does do I? I'm not sure if it returns anything. Maybe it just returns the same array. The .forEach (and/or the lambda in TypeScript) allows you to doctor up every item in an array so we could spay and neuter our cats.

 
 

Addendum 4/19/2018: Since writing last I have realized that .every should really be mentioned above and that it may be best to try to transform inside of a .filter instead of selectively return inside of a .map as if you try to just not return something in a .map loop you may end up with a null value sprinkled in your array.

 
 

Addendum 4/23/2018: I have learned today that you really cannot doctor stuff up with .filter like .map and what is more you really only want to return true or false from within a filter's loop. If you need to both map and filter you need to chain the two operations as best as I can tell. Also, note that you may pass an index in these loops as a second variable after the item at hand. Behold:

let yin = [13, 42, 69, 23];
let yang = [27, 42, 69, 86];
let venn = yin.map((y, index) => {
   if (yin[index] != yang[index]) return index;
}).filter(x => {
   if (x || x === 0) return true;
});
console.log(venn);

 
 

Addendum 5/1/2018: There is also a .find which does the same thing as .filter only instead of returning a collection it returns the first match. There is a .reduce too which is just crazy.

No comments:

Post a Comment