Common array methods in JavaScript

Thursday, Jul 30, 2020
JavaScript
const vehicles = []                 // empty array

vehicles.push("truck")              // return number of elements, 1
vehicles.push("car")                // 2
vehicles.length                     // 2, length is a property
vehicles[1]                         // "car"
vehicles.indexOf("truck")           // 0
vehicles.includes("truck")          // true
vehicles.join("-")                  // "truck-car" 

const x = []
x.push(1, 2, 3)                     // push multiple elements
x.reverse()                         // [3, 2, 1]
x.pop()                             // 1, x is now [3, 2]
1 in x                              // false

Methods using callbacks

.forEach(callback)

This is like a concise way of writing for loop. Does not return anything. Callback is applied to each element.

vehicles.forEach(vehicle => {
  console.log(vehicle.length);
        })

NOTE: Another way to loop through an array is for..of. This apparently is more robust (can be used in async methods, which I don't know yet) and allows the use of break and continue.

for (let vehicle of vehicles){
  console.log(vehicle.length);
}

.filter(callback)

Applies the callback to each element and returns an array that meets the condition of callback

vehicles.filter(vehicle => vehicle.length > 3);               // ["truck"]

.map(callback)

Transforms an array and return an array of same length with result from callback applied on each element

vehicles.map(vehicle => {
  vehicle.toUpperCase();            // ["TRUCK", "CAR"]
        })

.find(callback)

Returns the first item that meets the callback condition or undefined if none of the items meets the condition.

[1, 2, 3, 5, 3].find(item => item > 3)
// 5
[1, 2, 3, 5, 3].find(item => item > 5)
// undefined

.some(callback)

Returns a boolean true if one or more items meets the callback condition, false otherwise.

[1, 2, 3, 5, 3].some(item => item > 3)
// true

.every(callback)

Returns a boolean true only if all items meet the callback condition, false otherwise.

[1, 2, 3, 5, 3].every(item => item > 3)
// false

Removing items

let nums = [1, 2, 3, 4, 5, 6]

// start at index 2 and remove one item
nums.splice(2, 1)                   // [3], nums = [1, 2, 4, 5, 6]

// remove all items from index 3 and beyond
nums.splice(3)                      // [5, 6] nums = [1, 2, 4]

// empty an array
nums.length = 0                 

Destructure/Concatenate

let greet = "hello";

// array of characters from string
[...greet]                          // ["h", "e", "l", "l", "o"]

// destructure
let fullName = ["param", "singh"];
let [first, last] = fullNmae;       
console.log(first)                  // "param"

// concatenate
let firstGroup = ["red", "cyan"];
let secondGroup = ["blue", "green"];

let allColors = [...firstGroup, ...secondGroup];
console.log(allColors)              // ["red", "cyan", "blue", "green"]
console.log(last)                   // "singh"