Javascript built-in data structure - Array, part 3/3

This tutorial is a part of the Learn everything about Javascript in one course.

Javascript built-in data structure - Array, part 1/3 part 2/3, part 3/3 (current).

Filter array values with given condition, method filter()

Syntax array.filter(filterFunction(element[, index, [array]])[, additionalArg]).

Input Process Output
filterFunction: returns true to keep the element, false otherwise. user can define filterFunction that uses inputs (element, index, array, additionalArg) and return true or false to keep the element or not array of element satisfies filterFunction
element: current element for filter logic.
index: (optional) current element index.
array: (optional) original array.
additionalArg: (optional) additional input from upper scope to for filter logic
Modify original array Time complexity (worst)
NO O(n), n is orginal array length
array.js
// Filter array values with given condition, method filter
const arr18 = ['a', 'd', 'c', ['k', 6], ['g', 0], ['h', 1]]
console.log(arr18.filter((el) => typeof el === 'string')) // only return string element
// [ 'a', 'd', 'c' ]
console.log(arr18.filter((el) => Array.isArray(el))) // only return array element
// [ [ 'k', 6 ], [ 'g', 0 ], [ 'h', 1 ] ]
console.log(arr18.filter((el) => el[1] > 0)) // only return array element has second element greater than 0
// [ [ 'k', 6 ], [ 'h', 1 ] ]

// with additional bar variable
const bar = 2
const filtered = arr18.filter((el) => {
  return Array.isArray(el) && el[1] >= bar // only return array element has second element greater than `bar`
}, bar) 
console.log(filtered) // [ [ 'k', 6 ] ]

Determines if the array contains a value, method includes()

Syntax array.includes(valueToFind[, fromIndex]).

Input Process Output
valueToFind: value to see if it's in array
fromIndex: (optional) starting index to begin comparison
sequencially skim through the array (starting fromIndex if given) to compare its elements with given value true if found, false otherwise
Modify original array Time complexity (worst)
NO O(n), n is array length
array.js
// Determines if the array contains a value, method includes
const arr19 = [1,2,3, 'a', 'b', 'c']
console.log(arr19.includes(1)) // true
console.log(arr19.includes('a')) // true
console.log(arr19.includes('a', 4)) // false, start comparing from index 4
console.log(arr19.includes('d')) // false
console.log(arr19) // [ 1, 2, 3, 'a', 'b', 'c' ], original array NOT modified

Search the first index of a value in an array, method indexOf()

Syntax array.indexOf(searchElement[, fromIndex]).

Input Process Output
searchElement: value to see if it's in array
fromIndex: (optional) starting index to begin comparison
sequencially skim through the array forward (starting fromIndex if given) to find the index of given value first index if found, -1 otherwise
Modify original array Time complexity (worst)
NO O(n), n is array length
array.js
// Search the first index of a value in an array, method indexOf
const arr20 = [1,2,3, 'a', 'b', 1, 'b']
console.log(arr20.indexOf(1)) // 0
console.log(arr20.indexOf('b')) // 4
console.log(arr20.indexOf('b', 5)) // 6, start search from index 5
console.log(arr20.indexOf('d')) // -1
console.log(arr20) // [ 1, 2, 3, 'a', 'b', 1, 'b' ], original array NOT modified

Search the last index of a value in an array, method lastIndexOf()

Syntax array.lastIndexOf(searchElement[, fromIndex]).

Input Process Output
searchElement: value to see if it's in array
fromIndex: (optional) starting index to begin comparison
sequencially skim through the array backwards (starting fromIndex if given) to find the index of given value last index if found, -1 otherwise
Modify original array Time complexity (worst)
NO O(n), n is array length
array.js
// Search the last index of a value in an array, method lastIndexOf
const arr21 = [1,2,3, 'a', 'b', 1, 'b']
console.log(arr21.lastIndexOf(1)) // 5
console.log(arr21.lastIndexOf('b')) // 6
console.log(arr21.lastIndexOf('b', 5)) // 4, start search from index 5
console.log(arr21.lastIndexOf('d')) // -1
console.log(arr21) // [ 1, 2, 3, 'a', 'b', 1, 'b' ], original array NOT modified

Joins all elements of an array into a string, method join()

Syntax array.join([separator]).

Input Process Output
separator: (optional) string to add between elements convert all elements to string and join them to a string, put separator (comma , by default) in the between if provided a string of joined elements
Modify original array Time complexity (worst)
NO O(n), n is array length
array.js
// Joins all elements of an array into a string, method join
const arr22 = [1,2,3, 'a', 'b','c']
console.log(arr22.join()) // 1,2,3,a,b,c
console.log(arr22.join('')) // 123abc
console.log(arr22.join(' _ ')) // 1 _ 2 _ 3 _ a _ b _ c

Extracts a section of an array, method slice()

Syntax array.slice([begin[, end]]).

Input Process Output
begin: (optional) begin index to slice create new array by taking elements from begin index to the last index of the array an array
end: (optional) begin index to slice create new array by taking elements from begin index to the end index of the array an array
Modify original array Time complexity (worst)
NO O(n), n is array length
array.js
// Joins all elements of an array into a string, method join
const arr23 = [1,2,3, 'a', 'b','c']
console.log(arr23.slice()) // [ 1, 2, 3, 'a', 'b', 'c' ], same with original
console.log(arr23.slice(2)) // [ 3, 'a', 'b', 'c' ]
console.log(arr23.slice(2,4)) // [ 3, 'a' ]

Loop through each element of array, method forEach()

Syntax array.forEach(processFunction(currentValue [, index [, array]])[, additionalArg]).

Input Process Output
processFunction: function contains logic you want to do with each element. loop through each element and use processFunction logic to process that element undefined, return nothing, this method only provides a way to loop
currentValue: current element.
index: (optional) current element index.
array: (optional) original array.
additionalArg: (optional) additional input from upper scope to for filter logic
Modify original array Time complexity (worst)
NO O(n), n is orginal array length
array.js
// Joins all elements of an array into a string, method join
const arr24 = [1,2,3]
const extra = 1
const squared = arr24.forEach((el) => {
  console.log(el * el + extra)
}, extra)
// 2
// 5
// 10
console.log(squared) // undefined
console.log(arr24) // [ 1, 2, 3 ], original array NOT modified

Mapping array to a new array, method map()

Syntax array.map(mapFunction(currentValue [, index [, array]])[, additionalArg]).

Input Process Output
mapFunction: contains logic to do the mapping. Each time mapFunction executes, the returned value is added to new array map an array element to a new element for a new array new array with same length
currentValue: current element.
index: (optional) current element index.
array: (optional) original array.
additionalArg: (optional) additional input from upper scope to for filter logic
Modify original array Time complexity (worst)
NO O(n), n is orginal array length
array.js
// Mapping array to a new array, method map
const arr25 = [['a', 1], ['b', 2], ['c', 3]]
const year = 2020
// this mapping creates a sentence for each element with name age information
const p = arr25.map((el) => `The year is ${year} and '${el[0]}' is ${el[1]} year(s)old.`, year)
console.log(p) // 
// [
//   "The year is 2020 and 'a' is 1 year(s)old.",
//   "The year is 2020 and 'b' is 2 year(s)old.",
//   "The year is 2020 and 'c' is 3 year(s)old."
// ]
console.log(arr25) // [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ], original array NOT modified

Loop through all element and reduce, method reduce()

Syntax array.reduce(reduceFunction( accumulator, currentValue[, index[, array]] )[, initialValue]).

Input Process Output
reduceFunction: A function to execute on each element in the array (except for the first, if no initialValue is supplied) loop through all element in array and return a single value a single value
accumulator: The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback—or initialValue, if it was supplied.
currentValue: current element.
index: (optional) current element index.
array: (optional) original array.
initialValue: (optional) a value to use as the first argument to the first call of the callback. If no initialValue is supplied, the first element in the array will be used as the initial accumulator value and skipped as currentValue
Modify original array Time complexity (worst)
NO O(n), n is orginal array length
array.js
// Loop through all element and reduce, method reduce
const arr26 = [1,2,3]
const init = 4
// this mapping creates a sentence for each element with name age information
const r = arr26.reduce((acc, cur) => {
  return acc + cur // return value here will be `acc` for next reduceFunction call
}, 4)
console.log(r) // 10

Check if at least one element satisifies given condition, method some()

Syntax array.some(testFunction(element[, index[, array]])[, additionalArg]).

Input Process Output
testFunction: function to test for each element, taking three arguments loop through all element in array and return a single value true if at least one element satisfy, false otherwise.
element: The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback—or initialValue, if it was supplied.
index: (optional) current element index.
array: (optional) original array.
additionalArg: (optional) additional input from upper scope to for filter logic
Modify original array Time complexity (worst)
NO O(n), n is orginal array length
array.js
// Check if at least one element satisifies given condition, method some
const arr27 = [1,2,3]
console.log(arr27.some((el) => el > 2)) // true
console.log(arr27.some((el) => el < 0)) // false

Summary

  • Array has a lot of built-in methods. They are not there to overwhelm you. They are there so you can use them when you need to. And you will.
  • Remember what built-in methods can do while read/watch the lectures, syntax will become your muscle memory as you practice.