Ten JavaScript Array Methods You Should Know

Keywords: Javascript github

View the original text
For more information, please pay attention to it. GitHub

1,forEach()

Loop traversal array

const ARR = [1, 2, 3, 4, 5];
ARR.forEach(item => {
    console.log(item);// 1, 2, 3, 4, 5
})

2,includes()

Check whether the array contains the items passed in the method

const ARR = [1, 2, 3, 4, 5];
ARR.includes(2); // true
ARR.includes(8); // false

3,filter()

Create a new array to filter out eligible items in the new array

const ARR = [1, 2, 3, 4, 5];
const NEWARR = ARR.filter(num => num > 3); // [4, 5]
console.log(NEWARR); // [4, 5]
console.log(ARR); // [1, 2, 3, 4, 5]

4,map()

Create a new array by calling the provided function in each element.

const ARR = [1, 2, 3, 4, 5];
const NEWARR = ARR.map(num => num + 1);// [2, 3, 4, 5, 6]
console.log(ARR); // [1, 2, 3, 4, 5]

5,reduce()

Apply a function to each element in the accumulator and array (from left to right) and reduce it to a value

const ARR = [1, 2, 3, 4, 5];
const sum = arr.reduce((total, value) => total + value, 0);// 21

6,some()

Check that at least one array item meets this requirement. If it does, return "true" or "false".

const ARR = [1, 2, 3, 4, 5];
const NEWARR = ARR.some(num => num > 4); // true
const ANOTHERARR = ARR.some(num => num <= 0); // false

7,every()

Check that all items in the array conform to this condition. If it does, return "true" or "false".

const ARR = [1, 2, 3, 4, 5];
const NEWARR = ARR.every(num => num > 4); // false
const ANOTHERARR = ARR.every(num => num < 8); // true

8,sort()

Items used to sort/sort arrays in ascending or descending order.

const ARR = [1, 2, 3, 4, 5];
const alpha = ['e', 'a', 'c', 'u', 'y'];
 // Descending order
const DESCORDER = ARR.sort((a, b) => a > b ? -1 : 1);
// [5, 4, 3, 2, 1]

// Ascending order
const ASCORDER = alpha.sort((a, b) => a > b ? 1 : -1);
// ['a', 'c', 'e', 'u', 'y']

9,Array.from()

This turns all class arrays or iterations into arrays, especially when DOM is used, so that other array methods, such as reduce, map, filter, and so on, can be used.

const name = 'sueRimn'; // frugence
const nameArray = Array.from(name); // ['s', 'u', 'e', 'R', 'i', 'm', 'n']

When using DOM

const LIS = document.querySelectorAll('li');
const LISARRAY = Array.from(document.querySelectorAll('li'));

console.log(Array.isArray(LIS)); //  false
console.log(Array.isArray(LISARRAY));  //  true

10,Array.of()

Create arrays with each parameter passed in

const ARR = Array.of(1, 2, 3, 4, 5, 6); // [1, 2, 3, 4, 5, 6]

Posted by danf_1979 on Thu, 03 Oct 2019 16:10:38 -0700