Skip to main content

javascript-arrays

Arrays

  • an array is a type of object
  • built-in properties and methods
    • filter
    • sort
    • length
      • arrays are zero based

Array Methods

MethodDescription
.shiftremoves the first element of an array
.unshiftadds an element to the beginning of an array
.spliceadds, removes, or replaces an element at a given index.
.slicereturns a shallow copy of an array.
.forEachperform a function on each element in an array
.mapcreates a new array with the result of the provided function to each element
.reducecombine the array into one single value.
.filtercreate a new array with the elements that the provided function

.push()

let names = ["Abhi", "Mike", "Jeremy"];
names.push("G");
console.log(names);

.pop

let cities = ["New York", "Philly", "Orlando"];
cities.pop();

  • Array.every()
  • Array.find()
  • Array.findIndex()
  • Array.forEach()
  • Array.from()
  • Array.includes()
  • Array.isArray()
  • Array.lastIndexOf()
  • Array.reduceRight()
  • Array.some()

Ways to create a JavaScript Array

assignment operator: it will overwrite data in existing position

var array = [];
var array2 = [1,2,3,4,5];

constructor:

var array = Array(1,2,3,4,5);
array; // [1,2,3,4,5]

array OF

var array = Array.of(5);
array; // [5]
var array2 = Array.of(1,2,3,4,5,6, "string");
array2; // [1, 2, 3, 4, 5, 6, "string"]

[1, 2, 3]

  • Arrays don't enforce uniqueness of items. Duplicate entries are allowed.
  • Insertion order is kept
  • size (length) adjusts dynamically
  • Iterable (for loop)
var [
isEmployed = true,
hasKids,
hasLoans,
hasCreditcards,
...moreArgs
] = la.Factors;

Rest

rest parameter within dynamic function

var showCategories = function(productId, ...categories) {
console.log(categories instanceOf Array)
}

showCategories(123, 'search', 'sports')

Spread

opposite of rest

var prices = [12, 20, 18];
var maxPrice = Math.max(...prices);
console.log(maxPrice);

Rest Parameters

  • used in function definitions
  • the rest parameter syntax allows us to represent an indefinite number of arguments as an Array. This way changes to a function signature are less like to break code
function f(x, y=12) {
// y is 12 if not passed (or passed as undefined)
return x + y;
}
f(3) == 15
function f(x, ...y) {
// y is an Array
return x * y.length;
}
f(3, "hello", true) == 6
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6

Spread Operator

  • the spread operator allows us to split an Array argument into individual elements
  • used in function invocation

Array helper functions

Other Arrays

  • Jagged Arrays
  • empty param with comma
  • array of functions
const operations = [
{ name: "Add", action: function(a,b) { return a+b } },
{ name: "Subtract", action: function(a,b) { return a - b } },
{ name: "Multiply", action: function(a,b) { return a * b } },
{ name: "Divide", action: function(a,b) { return a / b } }
];
// filter here
operations.forEach(function(i) {
i.action();
});

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

Shallow copy using …

  1. The spread operator (…) is a convenient way to make a shallow copy of an array or object —when there is no nesting, it works great.
  2. 4 methods to shallow copy

Deep Copy

  1. use frameworks like lodash/ramda

NodeList vs Arrays

NodeLists and Arrays are two different things because NodeLists are actually not a JavaScript API, but a browser API.

Things like querySelectorAll() and getElementsByTagName() aren’t JavaScript methods, they’re browser APIs that let you access DOM elements. You can then manipulate them with JavaScript.

This used to confuse me like crazy, too, because JavaScript is the scripting language of the front end. Turns out, other languages can access these methods, too.

NodeLists differ from Arrays in another meaningful way, too.

They are often (but not always) live lists, meaning that if elements are removed or added to the DOM, the list updates automatically. querySelector() and querySelectorAll() return a static list (one that doesn’t update), but properties like .childNodes are live lists that will change as you manipulate the DOM (which can be a good or bad thing, depending on how you’re using it).

This is all made more confusing because arrays can contain nodes. The key way to think about NodeLists vs. Arrays: NodeLists are a language-agnostic way to access DOM elements, and Arrays are a JavaScript object you can use to contain collections of stuff.

They each have their own methods and properties, and you can convert a NodeList into an Array if you need to (but not the other way around).