Javascript Array Methods - 2

Javascript Array Methods - 2

Umut Cakmak
·Nov 9, 2021·

Subscribe to my newsletter and never miss my upcoming articles

reduce ()

With the reduce method, we can reduce the values in the array to a single value.

This method does not change the original array.

Initial value can be defined. If the initial value is not defined, the first value of the array is the initial value.

array.reduce(function(accumulator, currentValue, currentIndex, arr), initialValue)

  • accumulator : Collects the return value

  • currentValue = Required is the value of the current element.

  • currentIndex = Optional, index of current item .

  • array = Optional, array object to which current element belongs.

flat ()

let newArray = arr.flat(depth);

Creates a new array from all elements that have subarrays.

How deep the nested array structure should be flattened can be specified using the depth parameter. The default value is 1.

The Infinity parameter is used to concatenate all elements of substrings into a new string when you do not know the depth level.


findIndex()

It is used to find the index value of the array element that satisfies the first condition by looping the array elements and subjecting each array element to a condition in turn. Otherwise, it returns -1, indicating that no element passed the test.

  • value: This parameter is required and holds the value of the array elements

  • index: This parameter is optional and holds the index number of the array elements.

  • array: This parameter is optional and holds the array itself.

find()

The find method returns the value of the first element that satisfies the required condition. Otherwise, it returns undefined.

array.find(function(currentValue, index, arr),thisValue)

  • function: It is the function of the array running on each element.

  • currentValue: Required. Value of current element

  • index: Optional. Array index of current element

  • array: An optional parameter that holds the array object to which the current element belongs.

  • thisValue: This parameter is optional if a value is to be used as this value is passed to the function, otherwise an undefined value will be passed as of this value.

sort()

The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array.

By default, the sort() method sorts the array elements in ascending order with the smallest value first and the largest value last.

The sort() method casts elements to strings and compares the strings to determine the orders.

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

The sort() method does not work correctly for numbers. Because it sorts the numbers in alphabetical order.

Thanks for reading :)

Resources

mdn