nntrn
12/10/2018 - 12:00 AM

[js array snippets] a collection of (mostly) vanilla array snippets #js

[js array snippets] a collection of (mostly) vanilla array snippets #js

Array.matrix = function(numrows, numcols, initial){
   var arr = [];
   for (var i = 0; i < numrows; ++i){
      var columns = [];
      for (var j = 0; j < numcols; ++j){
         columns[j] = initial;
      }
      arr[i] = columns;
    }
    return arr;
}

//create a 3x5 matrix, with all values set to 0
var my2Darray = Array.matrix(3,4,0);

// source: Douglas Crockford (JavaScript: The Good Parts, p.64)
// taken from: http://www.stephanimoroni.com/how-to-create-a-2d-array-in-javascript/
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
// Returned object literal wrapped in parentheses
const getProfile = () => ({
  name: 'Glad Chinda',
  gender: 'Male',
  birthday: 'August 15'
});

// Pair of parentheses is omitted
const computeSquare = num => num * num;

// Pair of parentheses cannot be omitted
const addNumbers = (numA, numB) => numA + numB;

// The traditional function body wrapped in curly braces
// is used here to aid readability.
// Pair of parentheses cannot be omitted

const factorial = (n = 1) => {
  return (n <= 1) ? 1 : n * factorial(n - 1);
}

// Pair of parentheses cannot be omitted
const range = (...numbers) => Math.max(...numbers) - Math.min(...numbers);


// source: @gladchinda
// https://blog.logrocket.com/javascript-es6-5-new-abstractions-to-improve-your-code-54a369e82407
var arrayOfNumbers = arrayOfStrings.map(Number);

// convert array of strings to number


// Source:
// https://stackoverflow.com/a/21644513
  function createNewArr(e) {

    let newArr = Array(e.children.length).fill(null).map((x, i) => i);

    newArr.forEach((x, i) => { newArr[i] = e.children[i] });

    return newArr;
  }
function flatten(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
  }, []);
}

// source: 
// https://stackoverflow.com/a/15030117


function flatten(arr) {
  const flat = [].concat(...arr);
  return flat.some(Array.isArray) ? flatten(flat) : flat;
}

// source:
// https://stackoverflow.com/a/35548094
// 3 WAYS:

[...Array(6)].map(x=>0);
// [0, 0, 0, 0, 0, 0]

Array(6).fill(0);
// [0, 0, 0, 0, 0, 0]

Array(6).fill(null).map( (x,i) => i );
// [0, 1, 2, 3, 4, 5]

// source: 
// https://stackoverflow.com/a/49732119

Array is a special kind of object, suited to storing and managing ordered data items.

The declaration:

// square brackets (usual)
let arr = [item1, item2...];

// new Array (exceptionally rare)
let arr = new Array(item1, item2...);

The call to new Array(number) creates an array with the given length, but without elements.

We can use an array as a deque with the following operations:

  • push(...items) adds items to the end.
  • pop() removes the element from the end and returns it.
  • shift() removes the element from the beginning and returns it.
  • unshift(...items) adds items to the beginning.

To loop over the elements of the array:

  • for (let i=0; i<arr.length; i++) – works fastest, old-browser-compatible.
  • for (let item of arr) – the modern syntax for items only,
  • for (let i in arr) – never use.

Source: https://javascript.info/array

rest parameters

In ES6, rest parameters were introduced. A rest parameter is simply a named function parameter preceded by three dots(...). The rest parameter is assigned an array that contains the remaining arguments passed to a function. Here is how we can rewrite our previous sum() function using a rest parameter:

function sum(...args) {
  // Compute sum using array reduce()
  return args.reduce((a, b) => a + Number(b), 0);
}

There are a few things that are worth noting with regards to using rest parameters.

  1. You can only have one rest parameter for a function.
  2. The rest parameter, when present, must be the last parameter.
  3. A rest parameter is not the same as the arguments object. It only captures the remaining arguments after the other named parameters while the arguments object captures all the arguments passed to the function regardless.
  4. A rest parameter cannot be used in an object literal setter.

source: JavaScript ES6: 5 new abstractions to improve your code

arr.slice(-1)[0]
arr.slice(-1).pop()
// Both will return undefined if the array is empty.
// source: https://stackoverflow.com/a/12099341

var lastItem = anArray.pop();
// This returns the last element and removes it from the array
// source: https://stackoverflow.com/a/11034866

/* Methods that work with the end of the array: 
*************************************************/

let fruits = ["Apple", "Orange", "Pear"];

// pop:
// extracts the last element of the array and returns it:

// push:
// append the element to the end of the array:

fruits.pop() // "Pear"
fruits // ["Apple", "Orange"]

fruits.push("Lemon");
fruits // ["Apple", "Orange", "Pear", "Lemon"]


/* Methods that work with the beginning of the array:
*************************************************/

// shift: 
// extracts the first element of the array and returns it:

// unshift: 
// add the element to the beginning of the array 
// & returns the length

fruits.shift() // "Apple"
fruits // ["Orange", "Pear"]

fruits.unshift("Cinnamon"); // 4
fruits // ["Cinnamon", "Apple", "Orange", "Pear"]



/* PERFORMANCE
*************************************************/
// it is faster to work with the end of an array than with its beginning 
// elements after element[0] needs to be renumbered when removing/adding
// Methods push/pop run fast, while shift/unshift are slow

// stacks: LIFO (Last-In-First-Out), the latest pushed item is received first
// queues: FIFO (First-In-First-Out).
/* USING .reduce() *************/
function simpleArraySum(ar) {
  return ar.reduce(function (a, b) { return a + b }, 0)
}

// WITH ARROW FUNCTION @gladchinda
const sum = numbers.reduce((a, b) => a + Number(b), 0);

/* USING .forEach() *************/
function simpleArraySum2(ar, x = 0) {
  ar.forEach((num, index) => { x += num; });
  return x;
}



/* .notes *************/
// const arrSum = arr => arr.reduce((a, b) => a + b, 0)
// --------------------------------
// same thing as:
// --------------------------------
// arrSum = function (arr) {
//   return arr.reduce(function (a, b) {
//     return a + b
//   }, 0);
// }
/* --------------------------------
The function that we pass as the ==first parameter== of the reduce method receives two parameters, a and b. 
In this code, a is our accumulator. It will accumulate our sum as our function works. b is the current value being processed.

The second parameter of the reduce method is the initial value we wish to use. We’ve set our initial value to zero which allows us to use empty arrays with our arrSum functions.

source:
https://repl.it/@nntrn/simpleArraySum
*/
function transpose(matrix) {
  return matrix[0].map((col, i) => matrix.map(row => row[i]));
}

// map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. 
// callback is invoked only for indexes of the array which have assigned values; 
// it is not invoked for indexes which have been deleted or which have never been assigned values.

// INPUT
// [
//     [1,2,3],
//     [1,2,3],
//     [1,2,3],
// ]

// RESULT:
// [
//     [1,1,1],
//     [2,2,2],
//     [3,3,3],
// ]

// source:
// https://stackoverflow.com/a/17428705