Saturday, December 26, 2015

Taking an Array From Both Ends.

Warning. This post about arrays has no filter()!

 I love to manipulate arrays into doing my bidding, break 'em down, twist them to my will. It gives me a dirty thrill to take an array back to my homepage and push() in to it, Pop() a couple datum off its ass, then bring my neighbor Cat over and concat() into inserting herself into the situation.

Then after a <br>

...when the array starts to relax, thinks I've finished, I unshift("gears"), shove my data in its face, and when the array has taken all the data I have to give, I grab my [] cutter and  splice(n, 2, "it my initials", "ever so gently"). When the array winces, I offer it something to numb the pain then I join() it and we both lay on the floor, panting, strung out.

...If that passage didn't get arrays out of you, then maybe you need some hard facts about dealing with arrays to get your blood pumping.

Push:
Pushing is like doin' it doggy style with an array. i.e. Push shoves a new item (or items) into the back of an array.

syntax: array.push(newItem1 [, newItem2, etc]);
* anything inside of [within my examples indicates optional arguments... you shouldn't actually put square brackets in a functions arguments ]

NOTE, when you push to an array, you are changing the original array, so once you push to an array, you will only be able to reference the new, manipulated array.   

Also note, pushing an entire array (or arrays) into an existing array will not insert the contents of the inserted array, but will rather, create a multidimensional array… and if you are viewing multidimensional arrays in Google dev Tools, the data is truncated, but details of the contents of the internal arrays can be viewed by clicking on the arrow beside them.

 


Pop:
Popin’ a cap off in someone’s ass works exactly like poppin’ an item off of an array (where the array is the chamber of yo’ “gun” and the data is the “bullet” you just fired) well kinda… pop removes the last item from an array.
syntax: array.pop();

note —like push, you are manipulating the original array. However, unlike push, the parenthesis are left empty because you can only pop off one item from an array at a time.


Unshift:
If you want to shove data into an arrays face, use unshift. Unshift does to the 0th end of an array everything that push does to the array.length end of an array.
syntax: array.unshift(newItem1 [, newItem2, etc]);

note: an array can contain any combination of any type of data (strings, numbers, objects, etc)

syntax: array.unshift(item1 [item2, etc])


Shift:
Shifting data out of an array is like when you have a line of lovers before you and you don’t like the look of the one in front, so you ask that one to shift to one side and let the next one move to the front… except with an array rather than just shifting aside, you remove the item entirely. i.e. shift is like pop, but the item from the front of the array is remove rather than the item from the back. 

syntax: array.shift();


Slice:
Going back to the line of lovers. If there are one or two particularly enticing prospects in the middle of your line and you want to yank them out and deal with them privately before putting them back in line, you’d want to slice them out. Slice is a method that takes 2 arguments, the first of which is the index of the first item you wish to remove and the second argument is the position that follows the last item you want to remove. Slicing from an array removes items, but does not mutate the original array. So if you wish to reference the removed items in the future you should set them equal to a variable. NOTE if you only give one argument, slice will begin from the 0 index and slice items up to (but not including) the index you have given .

syntax: var sliced = array.slice([indexOfItem1,] indexAfterLastItem);

Splice:
If you’ve got some fuglies in your line and you just want them gone and put somewhere else, you can splice them out — and if you wish, you can splice in one or more replacements into the line. The splice method takes at least 2 arguments. The first is the index of the first item you wish to remove and the second argument is the total number of items you want to remove. If you are splicing IN to the array, you can add an additional argument for each item you would like to splice into the array. If you wish TO ADD ONLY (but not remove from the array), your second argument should be 0. Splicing mutates the original array, and you can also set a variable equal to the splice method you are calling to create a separate array containing any items you spliced out. NOTE If you put only one argument, all items after the first given index will be removed.

syntax: [var spliced =] array.splice(indexToBeginSplicing, numberOfItemsToSpliceOut [AdditionalitemsToSpliceIn]); 



Concat:

Like the story at the beginning of this blog post if you want to get inside two arrays at once, you have to concat. Because when you concat two arrays, the contents of the second array are inserted into the back of the first array.

note concat does not mutate the original array, so if you wish to reference the concatenated array in the future you must set a variable equal to the concatenated array.

syntax: var concatedArray = array1.concat(array2)
 














Friday, December 25, 2015

Searching For a True Match

Sometimes I just can't be bothered to deal with bullshit. When something isn't meeting my needs, I don't have time to fuck around with it. If (!"My boyfriend knows how to hit my g-spot") || "does my ass look good in these jeans" != true), then my boyfriend better figure out how to bang that ! out of that equation and I need to iterate through some more jeans before I execute buyThesePants(). Fortunately for these type of conundrums, there are a few particularly handy JS methods to sort through your data.

Filter: 
Allows you to insert each item from an array into a function that returns a boolean. If shoving the item into the function elicits a return value of "true" , then that item , along with any other truth-returning items from the original array, are inserted into a new array which becomes the return value of the filter.

syntax:var filteredArray = [array of data].filter(PUT BOOLEAN FUNCTION BETWEEN THESE PARENTHESIS);

example:
Holly, a scarlet-haired astrophysicist with a schedule even tighter than her waist line,  decided that it was time to stop playing the field and find a man to with whom she could start a family. Keen to keep her gene-pool as gingery fresh as possible, she decided to throw together a quick API to scrape data from hot-n-both-red.com, redI.com and crimsonlovers.com that would return the profiles of only the men that she deems to be desirable mates (ie 6'3 or taller, dog lovers making 65k minimum salary in a science related field). Below is an excerpt of some of the data she scraped:

var scrappedProfiles = [
 {name: "Dr Sex Panther", heightInCm: 160 , age: 35, income: 150000, profession: "Doctor", hobbies: "searching for my soul mate", pets: "has cats / likes dogs and cats", motto: "Trust me, I'm a doctor" },

{name:  "DJ Swizzle Stick", heightInCm: 175,  age: 25, income: 35000, profession: "valet",  hobbies: "gangsta rap, football, hunnies",  pets: "has cats / likes dogs and cats", motto: "I got 99 problems, but I'd like one more"},  
{name: "big D", heightInCm: 26 , age: 69, income: "mypenis", profession: "gigolo", hobbies: "blow, blowin', gettin' blown", pets: "yes I do", motto: "fuck bitches get money" },
{name: "Zenith", heightInCm: 185,  age: 25, income: 55000, profession: "Astronomy research", hobbies: "fishing, camping, walking my dogs",  pets: "has dogs / likes dogs", motto: "stay away from the dark side"}
];


After looking at the shape of the data, Holly designed the following filter that employed regex to search for certain key words in her prospective suitors profession and pet info as well as an assessment of the numerical value of their height and income. 

function dateable(profileObject){
  if( profileObject.income >= 65000 &&  profileObject.heightInCm >= 190 && profileObject.pets.search("dog") != -1     && profileObject.profession.search(/astro|doctor|sci|engineer|research|bio|chem|dev/i) != -1 ){
      return true;
  }
  return false;
}

var results = scrappedProfiles.filter(dateable);


Some:Checks to see if any individual items in an array meets the criteria of a given boolean and then returns true only if at least one item returns true when plugged into the boolean function. Some will return false only if there are no items within the array that meet the condition defined in the boolean function.

syntax:var filteredArray = [array of data].filter(PUT BOOLEAN FUNCTION BETWEEN THESE PARENTHESIS);

example: Frustrated that she was not getting any results back from her dating profile scraper. Holly, decided to broaden her search to include more sites (even some with men with less-favorable hair pigmentation). Not wishing to buy a membership to a site unless it contained some men that met her criteria, Holly modified her original function and ran it on prospective web sites:

function dateable(profileObject){
  if( profileObject.income >= 65000 &&  profileObject.heightInCm >= 190 && profileObject.pets.search("dog") != -1     && profileObject.profession.search(/astro|doctor|sci|engineer|research|bio|chem|dev/i) != -1 ){
      return true;
  }
  return false;
}

var useableSite = scrappedProfiles.some(dateable);

Every: 
Checks to see if all individual items in an array meet the criteria of a given boolean and then returns true only if every single item in the array gets a true result from the boolean or returns false if any of the items return false when plugged into the boolean function.

syntax:
var filteredArray = [array of data].every(PUT BOOLEAN FUNCTION BETWEEN THESE PARENTHESIS);


example:Once Holly had a few sites that she knew contained good prospects, she decided to apply one last function before joining a site. She wrote the below to search through the contents of each field on a user's profile and identify any disparaging language towards women.

function respectful(profileObject){
   var foulLanguage = [];
  
 Object.keys(profileObject).forEach(function(item, index){

  var value = profileObject[item]

 if(value.toString().search(/bitch|sukeban|whore|skintern|cunt|bobby soxer/i) != -1){
      foulLanguage.push(profileObject[item])
  }
       
})
   if (foulLanguage.length === 0 ){
      return true;
    }
  
  return false; 
  }

var useableSite = scrappedProfiles.every(respectful);