js array & common methods of string

Common methods of array

includes()
Used to judge whether there is an element in the array and return a Boolean value

const arr = [1, 2, 3, 4, 5]
console.log(arr.includes(4))
// true

forEach()
The most commonly used method of traversing an array. This method will not change the original array and has no return value.

const arr = [1, 2, 3, 4, 5]
arr.forEach( item => console.log(item) )
// 1
// 2
// 3
// 4
// 5

map()
map() is also a commonly used array traversal method. This method will return a new array, but will not change the original array. It returns undefined by default.

const arr = [1, 2, 3, 4, 5, 6]
const newArr = arr.map( item => item + 1 )
newArr // [2, 3, 4, 5, 6, 7]

// If there is no implicit or explicit return pointer, the resulting array is an undefined array with all elements
const arr = [1, 2, 3]
const newArr = arr.map( item => console.log(item) )
newArr // [undefined undefined undefined]

find()
This method finds the first qualified element in the array and returns it according to the search conditions. If it cannot be found, it returns undefined.

const arr = [1, 23, 45, 6, 7, 34]
const item = arr.find( item => item > 6 )
item // 23

findeIndex()
This method returns the index of the first qualified element according to the search criteria. If it cannot be found, it returns - 1.

const arr = [1, 23, 45, 6, 7, 34]
const item1 = arr.findIndex( item => item > 24 )
const item2 = arr.findIndex( item => item > 50 )
item1 // 2
item2 // -1

filter()
This method is used to filter the array and return a new array without changing the original array. If there is no qualified array, an empty array is returned.

const arr = [1, 2, 3, 4, 6, 8, 9, 12]
const newArr1 = arr.filter( item => item % 2 === 0 )
const newArr2 = arr.filter( item => item % 5 === 0 )
newArr1 // [2, 4, 6, 8, 12]
newArr2 // []

push() & pop()

  • The push() method adds an element to the end of the array and returns the length of the array.
const arr = [1, 2, 3, 4, 5]
const pushArr = arr.push(6)
arr // [1, 2, 3, 4, 5, 6]
pushArr // 6
  • The pop() method deletes the last element of the array and returns it.
const arr = [1, 2, 3, 4, 5, 6]
const popArr = arr.pop()
arr // [1, 2, 3, 4, 5]
popArr // 6

unshift() & shift()

  • The unshift() method adds an element at the beginning of the array and returns the length of the array.
const arr = [1, 2, 3]
const unshiftArr = arr.unshift(9)
arr // [9, 1, 2, 3]
unshiftArr // 4
  • The shift() method deletes the first element of the array and returns it
const arr = [1, 2, 3]
const shiftArr = arr.shift()
arr // [2, 3]
shiftArr // 1

concat()
This method splices new elements behind an array and can receive n parameters. The parameters can be of any type. If it is an array, splice the array with the original array. If it is other data types, add the element to the back of the element group. This method does not change the original array, but will return the spliced new array, so chain operation can be carried out.

const arr1 = [1, 2, 3]
const arr2 = ['a', 'b', 'c']
const newArr = arr1.concat(arr2, 'Ha ha ha').concat('hello world')

arr1 // [1, 2, 3]
newArr // [1, 2, 3, 'a', 'b', 'c', 'hahaha', 'hello world']

reverse()
This method can invert the array, return a new array, and change the original array.

const arr = [1, 2, 3, 4]
const reverseArr = arr.reverse()
arr // [4, 3, 2, 1]
reverseArr // [4, 3, 2, 1]

sort()
The sort() method sorts the array in French and can receive a function as a parameter. When no parameter is passed, the sort method will sort according to the internally defined ascending rules. This method returns the sorted array, and the element group will be changed.

const arr = [3, 5, 2, 7, 1, 0, 10, 2, 100, 76]
const sortArr = arr1.sort()
arr // [0, 1, 10, 100, 2, 2, 3, 5, 7, 76]
sortArr // [0, 1, 10, 100, 2, 2, 3, 5, 7, 76]
//The default sorting algorithm is to call the toString() transformation method of each array item, and sort the coded size of the compared string according to the way that the minimum value is in the front and the maximum value is in the back. That is, positive order and reverse order.

//positive sequence
sortArr = arr.sort((c, d) => c - d)
//Reverse order
sortArr = arr.sort((c, d) => d - c)

//give an example:
const arr = [
  { id: 4, name: 'michael' },
  { id: 2, name: 'kangkang' },
  { id: 3, name: 'meria' },
  { id: 1, name: 'jane' },
]
const newArr = arr.sort((a, b) => b.id - a.id)
newArr /* [
  { id: 4, name: 'michael' },
  { id: 3, name: 'meria' },
  { id: 2, name: 'kangkang' },
  { id: 1, name: 'jane' }
] */

join() & split()

  • The join() method forms the elements of the array into a string and receives only one parameter: the separator. This method returns the spliced string without changing the element group.
const arr = [1, 2, 3, 'hello', 'world']
const joinArr = arr.join(' ')
joinArr // 1 2 3 hello world

// Duplicate strings can be implemented through the join() method
const repeatStr = (str, n) => new Array(n).join(str)
const newArr = repeatStr('hi', 3)
newStr /*
'hihi'  The two separators hi only exist,
 Array(3)An array with a length of 3 is given, but the three elements in the array are blank,
hi separates these three blanks, which achieves the effect of repeating strings.*/
  • The split() method divides a string into an array, receives a parameter, and takes the parameter as the delimiter
const str = 'hello world'
const arr = str.split('w')
// Parameters that are used as delimiters are intercepted
arr // ['hello', 'orld']

every() & some()

  • The every() method takes a function as a parameter to judge whether each item in the array meets the conditions. It will return true only if all items in the array meet the conditions.
const arr = [1, 2, 3, 4, 5]
const trueArr = arr.every( item => item >= 1 )
const falseArr = arr.every( item => item > 5 )
trueArr // true
falseArr // false
  • The some() method takes a function as a parameter. As long as one item in the array meets the conditions, it returns true. If none of the conditions are met, it returns false.
const arr = [1, 2, 3, 4, 5]
const trueArr = arr.some(item => item > 1)
const falseArr = arr.some(item => item > 5)
trueArr // true
falseArr //false

indexOf() & lastIndexOf()
Both methods are used to find the index and receive two parameters. The first parameter is the element to be found, and the second parameter is the starting position of the search (the position of the first item and the last item by default). Will return the positive index of the element. The difference is that when there is a second parameter, indexOf() only looks up the elements after the element, and lastIndexOf() only looks up the elements before the element. The index is returned if the element is found, and - 1 is returned if it is not found.

const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
//Look up b this element from index 0
const index = arr.indexOf('b', 0)
//Look up b this element from index 0
const lastIndex = arr.lastIndexOf('b', 0)

index // 1
lastIndex // -1

slice()
slice(start, end) receives two parameters (index of elements) and returns the element array between [start, end], without changing the element group.

const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
const sliceArr = arr.slice(2, 6)
sliceArr // ["c", "d", "e", "f"]

//slice() can also accept negative numbers as parameters, - 1 is the penultimate element, - 2 is the penultimate element, and so on

splice()
This method adds / deletes items to / from the array, and then returns the deleted items. This method will change the original array.

arr.splice(index, howmany, item)
index // Required. Integer specifying where to add / delete items. Negative numbers can be used
howmany //Required. Number of items to delete. If set to 0, the item will not be deleted
item //Optional, a new item added to the item number group
const arr = [1, 2, 3, 4, 5]
// Starting from the position with index 2, delete 3 and add 6, 7 and 8
const spliceArr = arr.splice(2, 3, 6, 7, 8)
arr // [1, 2, 6, 7, 8]
spliceArr // [3, 4, 5]

reduce()
Reduce executes the callback function for each element in the array in turn, excluding the elements deleted or never assigned in the array. It accepts four parameters: initial value (or the return value of the previous callback function), current element value, current index and the array calling reduce.
Syntax:

arr.reduce(callback,[initialValue])
callback (Function that executes each value in the array, including four parameters)

    1,previousValue (The value returned by the last call callback, or the initial value provided( initialValue))
    2,currentValue (Elements currently being processed in the array)
    3,index (Index of the current element in the array)
    4,array (call reduce (array of)

initialValue (As the first call callback (the first parameter of.)

Application:

arr.reduce((prev, current, index, array) => {}, initaialValue)

Array summation
const arr = [1, 2, 3, 4]
const sum = arr.reduce((prev, current) => prev + current, 0)
sum // 10

Array quadrature
const arr = [1, 2, 3, 4]
const pow = arr.reduce((prev, current) => prev * current)
pow //24

Array de duplication
const arr = [1, 2, 4, 4, 5, 6, 2, 4, 3]
const slimArr = arr.reduce((prev, current) => {
    if(prev.includes(current)) {
        return prve
    } else {
        return prev.concat(current)
    }
})

Tags: Javascript array

Posted by Renegade85 on Fri, 29 Apr 2022 12:41:59 +0300