/JS_Array_Method_Reference

Summary of most use Array methods in JavaScript

Primary LanguageJavaScript

JS_Array_Method_Reference

Here is the summary for most use Array method in JS

num Description Syntax Example Note
1 Converting Arrays to Strings object.toString(); const arr = ["a","b","c"]; arr.toStings(); //output : a,b,c
  • convert with comma separated
  • convert object to string
arr.join([separator]); const arr = ["a","b","c"]; arr.join(""); //output : abc
  • Have options to join without comma by .join("") empty string
  • Default will be with comma separation
  • Can join with a specified separator
  • this method will not change the original array.
*sting Convert string to array str.split() const str = "abc"; const arr = str.split("") // ["a","b","c"] empty sting split between char (" ") split between empty space
  • split() method does not change the original string and
  • return new array
2 Remove(pop) or add(push) last element in array arr.pop() / arr.push() let arr1 = ["a","b","c"]; let arr2 = arr1.pop() // output: arr1:["a","b"] arr2: ["c"]
  • Changes the length of an array.
  • using.delete() to remove array will let undefined holes in array, use pop() instead
3 Remove(shift) or add(unshift) first element in array arr.shift() / arr.unshift() let arr1 = ["a","b","c"]; let arr2 = arr1.shift() // output: arr1:["b","c"] arr2: ["a"]
  • Changes the length of an array.
4 Returns the selected elements in an array, as a new array object. array.slice(from, until) let arr1 = [1,2,3,4,5]; let arr2 = arr1.slice(1,3) //return [2,3] until index 3 but not include 3
  • DO NOT change the length of an array.
5 Adds/removes items to/from an array arr.splice(starting index, number of elements to remove when call, element to add);
  1. let arr = [1,2,3,4,5]; let arr2 = arr.splice(2); // Every element starting from index 2, will be removed [3,4,5]
  2. array.splice(0, 0, 'a', 'b'); //staring index 0, nothing to remove, add element ["a","b"]
  • similar to pop but can specify which elements to remove or add
  • Changes the length of an array.
6 filter array arr.filter(function return true of false) see example.js do not change the original array
7 convert array to new array, take object with specific key value map() see example.js Note
8 find key in the array ,check the return value, true of false find() see example.js Note
9 take the each item in the array and do something with it forEach() see example.js Do not return anything, similar to for loop
10 combine each item in the array to one sum total reduce() see example.js reduce ((1. current value, 2. array item) =>{ return calculation}, starting point)
11 return true or false if the parametal in the include method in the array includes() see example.js Note