Thursday, January 5, 2017

JS30 Challenge Day4 - Array functions

Day 4


Some basic concepts revisited:

Filter:
You pass a function to a filter which will loop over every item in the array

We can use console.table instead of console.log to display it pretty 

I learned a fancy and compact way to return a value instead of an if-statement returning ‘true’.

const fifteen=inventors.filter(inventor => inventor.year <1600 && inventor.year>= 1500);

Map:
Takes in an array, modifies it and returns a new array

We use + for concatenation in JS and . in PHP

Reduce:
Builds something on each entry

const tot = inventors.reduce((total,inventor) => {return total+ inventor.passed-inventor.year},0);

The 0 at the end is to set the total to an initial value of 0
So following this idea, you could as well initialize it to a 5, for example, for some different kind of functionality.

Reminder: querySelectorAll does not return an Array but returns a NodeList
Array.from(some_nodeList); converts a NodeList into Array

textContent:
const de= links.map(link=> link.textContent);
link.textContent returns the names enclosed within ‘a’ tags where links is a list of ‘a’ tags on the page

Reduce explained:

const transport = data.reduce(function(obj,item){

      if(!obj[item]) obj[item]=0;
      obj[item]++;
      return obj;

    },{});

In the code above, obj is an element passed to the reduce function which will gather data over each iteration. For each unique element in an array, an obj will be created. The name of the element goes into the index of the obj. So every time an element is found, the value of that item ( the element from the data array) will increase by 1 in the obj object. To initialize the object as a blank object, we have added {} at the end.

In short, the parameters of a reduce function should match the structure of an element in the calling array. This could be a name value pair or simply a variable like total which accrues count over time and is not part of the array element originally. It may act as just another variable as we saw in the first usage of reduce function or it may act as an object containing its own processed values.


No comments:

Post a Comment