Arrays and Objects

Array.prototype– Allows additional properties of all array objects
Array.from– Creates a new array from an array-like object- newArr = Array.from(arrX);
Array.isArray– Return true or false as test result of an object- Format: Array.isArray(objectX);
Array.of– Creates a new instance basing of the original object- Format: Array.of(arrX);
Array.prototype.toString– Since the Array type is a derivative of the Object type, this method overrides the Object.prototype.toString one. The function is as named.- Format: Array.prototype.toString(arr);
Array.prototype.values()–  Returns a new Array Iterator object that contains the values for each index in the array.
find– Returns the value of the first found element in the array. Result equals undefined if not found.- Format: arr.find(callback[, thisArg])- Available in ES6- Returns one element value
findIndex– Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
indexOf– Find the matching item in the array and return its index position- Format: arr.indexOf(searchItem)
lastIndexOf– Return the index position of the last matching item- Format: arr.lastIndexOf(searchElement, fromIndex)
include– Return true of false value indicating a matching element in the array- Format: arr.include(searchItem);
some–  Returns true if at least one element in this array satisfies the provided testing function.
keys– Returns index positions of the elements in the array- Format: Object.keys(arr)  or arr.keys()- The first format ignore holes, while the second format doesn’t
filter– Creates a new array with all of the elements of this array for which the provided filtering function returns true.
reduce– Creates a new array with the results of calling a provided function on every element in this array.- Format: (function(accumulator, currentElement, indexOfCurrentElement) {}, startingIndex)- The return of the function above will become the value of the accumulator
reduceRight–  Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
exec– Execute RegExp statement toward an object- Format: specialChars.exec(object)    where specialChars=/d(b+)(d)/i;  and testObj={[‘abcd’],[‘effasd’]}
call– Calls the object, parses it into the method with a provided function- This method is generic, and it is being phased out in newer versions of Javascript. Thus, Array.prototypes,method can be called directly into (object,function) without using call.- Format: Array.prototype.{method}.call(object,function)- Example: if (Array.prototype.every.call(str, function isLetter (char) {return char >= ‘a’ && char <= ‘z’; })) {  console.log(“The string ‘” + str + “‘ contains only letters!”);}
apply– Used as “Array.prototype.{method}.apply(objects)” where method shall be applied toward the inside objects- This method is also generic, which will disappear.- 
each
forEach– This is very useful to replace for loops to make the codes more clean.- Reference to original collection- Default ‘this’ value in the callback- Returns ‘undefined’- Each iteration of this method has an immediate impact on the elements of the affected array.- Format: arr.forEach(function(item,index,array){ some codes})- Example of usage:  arr2.forEach(function(newItem){    var flag=0;    // Loops through current inventory to update inventory. If item is new, set the flag    arr1.forEach(function(existingItem){      if (newItem[1]===existingItem[1]) {existingItem[0]+=newItem[0]; flag=1;}   });      // item[0] holds the value and item[1] holds the label    // Insert item if it’s new    if (flag===0){      arr1.push(newItem);    }     });
every– Returns true if every element in this array satisfies the provided testing function.
slice– Extracts elements of an existing array into a new copy- Format: arr.slice(begin,end)- The begin position is included, while the end marker element will not be included in the extraction
splice– Format: splice(startingIndex, removeItemCount, addItem1…)- If the starting index is a negative number, that is interpreted as the element index counting from the last item of the array- How to remove an element and its index from the array:    arr.splice(arr.indexOf(elementToRemove),1,NaN);- How to remove last two elements of an array: arr.slice(-2);- How to remove first two elements of an array: arr.slice(2);
concat– Concatenate the result or elements into base array-  Format: arr1.concat(arr2)
join– Joints all elements within the array into a string- Format: arr.join(separator);- The separator is often “” (no-space), ” ” (space), ‘-‘ (dash), ‘\n’ (new line)
map– Calling a provided function on every element in this array.- Different from the ‘forEach’ method in the way the this function returns the results of all iterations into a new array of the same size as the original.- Example of an alternative to running two ‘for’ loops:arr1.map(function(item1) {    return arr2.map(function(item2) {      if (item1[1] === item2[1]) {   item1[0] = item1[0] + item2[0];  }    });  });
pop– remove the last element in the array- Format: arr.pop()
push– insert an element into the last position of the array- arr.push(newElement)
shift– Remove the first item in the array- Format: arr.shift()
unshift– Add an item to the front in the array- Format arr.unshift(item)
reverse– Reverse the elements of an array- Format: arr.reverse();
sort– Sort elements within an array- Example of sorting numerical values:arr.sort(function (a,b){return a-b;});- Example of sorting by alphabets:items.sort(function(a, b) {  var nameA = a.name.toUpperCase(); // ignore upper and lowercase  var nameB = b.name.toUpperCase(); // ignore upper and lowercase  if (nameA < nameB) {    return -1;  }  if (nameA > nameB) {    return 1;  }  return 0; // when names are equal});- Example sorting nested arrays, where arr[…][0] contains the labels to be sortedarr.sort(function(currItem, nextItem) {     return currItem[0] > nextItem[0];   });
length– return a number representing the count of array elements

Useful lines:

  • Convert arguments into array:   var arr = Array.prototype.slice.call(arguments);
  • Remove duplicates within an array:   .filter(function(elem, index, self) { return index == self.indexOf(elem);})
  • Sum values in a one-dimensional array: .reduce(function (a, b) {return a + b;}, 0)     OR    .reduce((a, b) => a + b, 0).toFixed(2);  where 2 is the #’s of trailing digits desired
  • Flatten nested arrays: var flattened = [].concat.apply([], nestedArrays);
  • Remove all non-numerical values from an array: .filter(function(element) {return !isNaN(parseFloat(element)) && isFinite(element );});
  • Remove an element and its index from the array:    arr.splice(arr.indexOf(elementToRemove),1,NaN);

Notes:

  • To access an object inside an array, one must use notations inside a brackets such as: USA[‘California’] NOT USA[California]
  • […{object}] — the “spread operator” gathers up all elements within the object

Leave a Reply

Your email address will not be published. Required fields are marked *