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 |
|
arr.join([separator]); | const arr = ["a","b","c"]; arr.join(""); //output : abc |
|
||
*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 |
|
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"] |
|
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"] |
|
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 |
|
5 | Adds/removes items to/from an array | arr.splice(starting index, number of elements to remove when call, element to add); |
|
|
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 |