Array is a data type that we use very frequently. Whether we can master the advanced methods of array will directly affect our work efficiency. Before starting this article, take a look at the previous article on array traversal, which will not be covered in this article:

1. Filter method

The **filter()** method creates a new array containing all the elements of the test implemented by the provided function. ,

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

1.1 parameter

  • callback

    A function that tests each element of an array. Returning true indicates that the element passed the test and is retained, false does not. It takes the following three parameters:

    Element The element in the array that is currently being processed. Index Indicates the index of the element being processed in the array. Array optionally calls the array itself of filter.

  • ThisArg optional

    The value used for this when callback is executed.

1.2 The return value

A new array of elements that pass the test, or an empty array if none of the array elements pass the test.

  • filterDoes not change the original array, it returns the filtered new array.

1.3 describe

Filter calls callback once for each element in the array and creates a new array with all elements that cause callback to return true or its equivalent. Callback will only be called on indexes that have been assigned, not indexes that have been deleted or never assigned. Elements that do not pass the callback test are skipped and not included in the new array.

Callback is called with three arguments:

  1. The value of the element
  2. Index of an element
  3. The array itself being iterated over

If a thisArg argument is provided to filter, it will be used as this when callback is called. Otherwise, callback’s this value will be global in non-strict mode and undefined in strict mode. The value that the callback eventually observes is determined according to the rule of “this” that functions normally see.

1.4 Example: People with arrays greater than 5

Let arr = [5, 6, 8, 10, 24]; let arr = [5, 6, 8, 10, 24]; let bigThanEightArr = arr.filter((item, index, arr) => { // console.log(item, index, arr); return item > 6 }, this); console.log(bigThanEightArr); / /,10,24 [8]Copy the code

The above code is how to use the filter method, which takes two arguments and ultimately returns a new array. The two parameters of filter are:

The first is the callback function. The callback takes three arguments: the current element, the current element’s index, and the original array. You can perform some operations in the callback to determine whether to keep the element. If you want to keep the element, the callback returns true, and if it does not, the callback returns false

In the above code, item > 5 returns true as long as the current element is greater than 5, thereby preserving the value, so the new array is [6, 8, 9].

The second argument specifies what this refers to when the callback is executed. This parameter is not set in the code above, so when this is printed in the callback, it points to the window object

2. Processing method MAP

The **map()** method creates a new array with the result that each element in the array is the value returned by calling the supplied function once.

var new_array = arr.map(function callback(currentValue[, index[, array]]) { // Return element for new_array }[, thisArg])

2.1 parameter

  • Callback Generates a function for a new array element, taking three arguments:
  • currentValue: The current element being processed in the callback array.
  • indexOptional:callbackThe index of the current element being processed in the array.
  • arrayOptional:mapAn array of method calls.
  • thisArgOptional: ExecutecallbackFunction time values are used asthis.

2.2 the return value

A new array consisting of the result of each element of the original array executing the callback function.

2.3 case:Map example: Multiply each element of the original array by 2

Let doubleArr = arr.map((item, index, arr) => item * 2); console.log(doubleArr); //[10, 12, 16, 20, 48]Copy the code

2.4 The following code uses an array of objects to recreate a formatted array.

var kvArray = [{key: 1, value: 10}, {key: 2, value: 20}, {key: 3, value: 30}]; var reformattedArray = kvArray.map(function(obj) { var rObj = {}; rObj[obj.key] = obj.value; return rObj; }); [{key: 1, value: 10}, // {key: 2, value: 10}, // reformattedArray array: [{1: 10}, {2: 20}, {3: 30}] 20}, // {key: 3, value: 30}]Copy the code

3. Reduce

3.1 parameter

callback

The function that executes each value in the array (except the first value if no initialValue is provided), with four arguments:

accumulator

  • currentValue

    The element in the array being processed.

  • The index of the optional

    The index of the current element being processed in the array. If initialValue is provided, the starting index is 0, otherwise it starts from index 1.

  • An array of optional

    An array that calls reduce()

The initialValue optional

As the value of the first argument when the callback function is first called. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.

3.2 the return value

The cumulative processing result of the function

3.3 describe

Reduce executes a callback function for each element in the array, excluding elements that were deleted or never assigned, and takes four arguments:

  • An accumulator cumulative device
  • The current value currentValue
  • CurrentIndex indicates the currentIndex
  • Array an array

Accumulator and currentValue are two different values when the callback function is first executed:

  • == if calledreduce()providesinitialValue.accumulatorValues forinitialValue.currentValueTake the first value in the array; = =
  • == If not providedinitialValue, thenaccumulatorTake the first value in the array,currentValueTake the second value in the array. = =

** Note: ** If no initialValue is provided, Reduce executes the callback method from index 1, skipping the first index. If initialValue is provided, start at index 0.

If the array is empty and no initialValue is provided, TypeError (regardless of location) is raised and no initialValue is provided, or initialValue is provided but the array is empty, this unique value is returned and callback is not executed.

How does 3.4 Reduce work?

If we run the next reduce() code:

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
  return accumulator + currentValue;
});
Copy the code

Callback is called four times, and the parameters and return values of each call are as follows:

callback accumulator currentValue currentIndex array return value
first call 0 1 1 [0, 1, 2, 3, 4] 1
second call 1 2 2 [0, 1, 2, 3, 4] 3
third call 3 3 3 [0, 1, 2, 3, 4] 6
fourth call 6 4 4 [0, 1, 2, 3, 4] 10

The value returned by reduce will be the last callback return value (10).

You can also use arrow functions instead of full functions. The following code produces the same output as the code above:

[0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr );
Copy the code

If you want to provide an initial value as the second argument to the reduce() method, here’s how it works and what happens:

[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
    return accumulator + currentValue
}, 10)
Copy the code
callback accumulator currentValue currentIndex array return value
first call 10 0 0 [0, 1, 2, 3, 4] 10
second call 10 1 1 [0, 1, 2, 3, 4] 11
third call 11 2 2 [0, 1, 2, 3, 4] 13
fourth call 13 3 3 [0, 1, 2, 3, 4] 16
fifth call 16 4 4 [0, 1, 2, 3, 4] 20

In this case reduce() returns a value of 20.

3.4 the reduce practice

3.4.1 There are no original parameters

// 1.reduce has no original arguments let arr = [10, 15, 8, 6, 11, false, 'hello']; let newArr = arr.reduce((previousValue, currentValue, index, arr) => { console.log(previousValue, currentValue, index, arr); return previousValue = previousValue + currentValue; }) console.log(newArr); //50helloCopy the code

3.4.2 There are original parameters

Reduce let newArr2 = arr. Reduce ((previousValue, currentValue, index, arr) => { return previousValue += currentValue; }, 10); console.log(newArr2); //60helloCopy the code

Rule 3.4.3Sums the values in an array of objects

To accumulate the values contained in the array of objects, you must provide initial values so that each item passes through your function correctly.

var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
    (accumulator, currentValue) => accumulator + currentValue.x
    ,initialValue
);

console.log(sum) // logs 6
Copy the code

3.4.4 Convert a two-dimensional array to a one-dimensional array

var flattened = [[0, 1], [2, 3], [4, 5]].reduce( function(a, b) { return a.concat(b); } []); // flattened is [0, 1, 2, 3, 4, 5]Copy the code

Find an element of an array

The **find()** method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined

4.1grammar

arr.find(callback[, thisArg])
Copy the code

4.2 parameter

  • callback

    A function that executes on each item of the array and takes three arguments: element The element currently traversed. Index Indicates the current traversal index. Array The optional array itself.

  • ThisArg optional

    The object used as this when the callback is executed.

4.3 The return value

The value of the first element in the array that satisfies the provided test function, otherwise undefined is returned.

4.4 describe

The find method executes a callback function on each element in the array until a callback returns true. When such an element is found, the method immediately returns the value of the element, otherwise undefined. Note that the callback function is called for every index in the array from 0 to Length-1, not just the assigned indexes, which means that this method is less efficient for sparse arrays than methods that traverse only the indexes with values.

The callback function takes three parameters: the value of the current element, the index of the current element, and the array itself.

If thisArg is provided, it will be this for each callback, if not, undefined will be used.

The find method does not change the array.

The index range of the element is determined the first time the callback function is called, so new elements added to the array after the find method starts executing will not be accessed by the callback function. If the value of an element in the array that has not been accessed by the callback function is changed by the callback function, then the value will be the current value accessed by the callback function based on its index in the array. The deleted element is still accessed, but its value is undefined.

4.5 case

let arr = [10, 5, 6, 80, 12]; let element = arr.find((currentValue, index, arr) => { return currentValue > 70 }) console.log(element); / / 80Copy the code

Find the index of an array element

The indIndex() method returns the index of the first element in the array that satisfies the provided test function. Returns -1 if no corresponding element is found.

5.1grammar

arr.findIndex(callback[, thisArg])
Copy the code

5.2parameter

  • callback

    This callback is executed for each element in the array, automatically passing in the following three arguments: Element The current element. Index Indicates the index of the current element. Array An array that calls findIndex.

  • thisArg

    Optional. Callback is executed as the value of this object.

5.3 The return value

Array by providing the index of the first element of the test function. Otherwise, -1 is returned

5.4 describe

The findIndex method calls each array index in the array 0.. Leng-1 (inclusive) executes the callback function once until a callback function is found that returns a true (mandatory true) value. If such an element is found, findIndex immediately returns the index of that element. FindIndex returns -1 if the callback never returns true, or if the length of the array is 0. Unlike some other array methods, such as Array#some, in a sparse array, the callback function is called even for indexes of items that do not exist in the array.

The callback function is called with three arguments: the value of the element, the index of the element, and the array to be iterated over.

If a thisArg argument is provided to findIndex, it will be used as this every time the callback is called. If not provided, undefined will be used.

FindIndex does not modify the array being called.

The index range of the element is determined the first time the callback function is called, so new elements added to the array after the findIndex method starts execution will not be accessed by the callback function. If the value of an element in the array that has not been accessed by the callback function is changed by the callback function, then the value will be the current value accessed by the callback function based on its index in the array. Deleted elements can still be accessed.

5.5 Finds the index of the first prime element in an array

// The following example looks for the index of an element of a prime in an array (-1 if no prime exists). function isPrime(element, index, array) { var start = 2; While (start <= math.sqrt (element)) {if (element % start++ < 1) {return false; } } return element > 1; } console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found console.log([4, 6, 7, 12].findIndex(isPrime)); / / 2Copy the code

At least 1 element == has passed the provided function test (some).

The **some()** method tests that at least one element in the array passes the provided function test. It returns a Boolean value.

** Note: ** If tested with an empty array, it returns false in any case.

6.1grammar

arr.some(callback(element[, index[, array]])[, thisArg])
Copy the code

6.2parameter

  • callback

    A function that tests each element and takes three arguments: the element being processed in the Element array. Index Indicates the index value of the element being processed in the optional array. Array Optional some() array to be called.

  • ThisArg optional

    The this value used when executing callback.

6.3 The return value

If at least one element in the array passes the test, the callback returns true. The return value is false only if all elements fail the callback test.

6.4 describe

Some () performs a callback function once for each element in the array until a value is found that causes the callback to return a “true” value (which can be converted to a Boolean value of true). If such a value is found, some() will immediately return true. Otherwise, some() returns false. Callback will only be called on indexes that “have a value”, not indexes that have been deleted or never assigned a value.

Callback is called with three arguments: the value of the element, the index of the element, and the array to be iterated over.

If a thisArg argument is supplied to some(), it will be used as the this value of the callback being called. Otherwise, its this value will be undefined. The value of this is ultimately observed by callback, which is determined by the usual rules for determining this seen by a function.

Some () is called without changing the array.

Some () traverses the range of elements in the first call to callback. It was already decided. The value added to the array after calling some() is not accessed by the callback. If an element in the array that has not yet been accessed is changed by the callback, the value passed to the callback is the value at which some() accessed it. Deleted elements will not be accessed.

6.5 case

6.5.1 Tests the value of an array element

The following example checks if any element in an array is greater than 10.

function isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
Copy the code

Tactical fix packs for 6.5.2Use the arrow function to test the value of an array element

The arrow function can implement the same use case with a more concise syntax.

[2, 5, 8, 1, 4].some(x => x > 10);  // false
[12, 5, 8, 1, 4].some(x => x > 10); // true
Copy the code

6.5.3 Determines whether a value exists in an array element

This example mimics the includes() method, and the callback returns true if the element exists in the array:

var fruits = ['apple', 'banana', 'mango', 'guava'];

function checkAvailability(arr, val) {
  return arr.some(function(arrVal) {
    return val === arrVal;
  });
}

checkAvailability(fruits, 'kela');   // false
checkAvailability(fruits, 'banana'); // true
Copy the code

6.5.4 Use the arrow function to determine whether a value exists in an array element

var fruits = ['apple', 'banana', 'mango', 'guava'];

function checkAvailability(arr, val) {
  return arr.some(arrVal => val === arrVal);
}

checkAvailability(fruits, 'kela');   // false
checkAvailability(fruits, 'banana'); // true
Copy the code

6.5.5 Converts any value to a Boolean type

var TRUTHY_VALUES = [true, 'true', 1];

function getBoolean(value) {
  'use strict';

  if (typeof value === 'string') {
    value = value.toLowerCase().trim();
  }

  return TRUTHY_VALUES.some(function(t) {
    return t === value;
  });
}

getBoolean(false);   // false
getBoolean('false'); // false
getBoolean(1);       // true
getBoolean('true');  // true
Copy the code

Test if all elements of an array == pass the test of a given function (every)

The **every()** method tests whether all elements in an array pass the test of a given function. It returns a Boolean value.

Note: If an empty array is received, this method returns true in all cases.

7.1 grammar

arr.every(callback(element[, index[, array]])[, thisArg])
Copy the code

7.2 parameter

  • callback

    The function used to test each element, which can take three arguments: element for the current value of the test. Index The index of the current value that can be selected for the test. Array Optionally calls the current array of every.

  • thisArg

    The this value used when executing callback.

7.3 The return value

Return true if the callback returns truthy each time, false otherwise.

7.4 describe

The every method executes the callback function once for each element in the array until it finds an element that causes the callback to return Falsy. If one is found, the every method will immediately return false. Otherwise, callback returns true for each element, and every returns true. Callback will only be called for indexes that have already been assigned a value. Not called for indexes that are deleted or never assigned.

Callback can be called with three parameters: the element value, the element index, and the original array.

If a thisArg argument is provided for every, it is the this value when callback is called. If omitted, the value of this when callback is called is global in non-strict mode, and undefined in strict mode. See this entry for details.

Every does not change the array.

The scope of every traversal is determined before the first callback is called. Elements added to the array after every are called are not accessed by the callback. If an element in the array is changed, they pass the value every at the moment they are accessed to the callback. Elements that are deleted or that have never been assigned a value will not be accessed.

Every, like the word “all” in mathematics, returns true when all elements meet the criteria. Because of this, passing an empty array returns true anyway. (This is unconditionally true: just because an empty set has no elements, all its elements conform to a given condition.)

7.5 case

7.5.1Checks the size of all array elements

The following example checks whether all elements in an array are greater than 10.

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
Copy the code

7.5.2 Using the arrow function

The arrow function provides a shorter syntax for the above inspection process.

[12, 5, 8, 130, 44].every(x => x >= 10); // false
[12, 54, 18, 130, 44].every(x => x >= 10); // true
Copy the code

Sort by sort

The **sort()** method sorts the elements of an array using an in-place algorithm and returns the array. The default sort order is built when converting elements to strings and then comparing their UTF-16 code unit value sequences

8.1 grammar

arr.sort([compareFunction])
Copy the code

8.2 parameter

  • CompareFunction optional

    Used to specify functions that are sorted in a certain order. If omitted, the element is sorted by the Unicode loci of each character in the converted string. FirstEl is the first element used for comparison. SecondEl The second element used for comparison.

8.3 The return value

Sorted array. Note that the array is sorted in place and is not copied.

8.4 describe

If compareFunction is not specified, the element is sorted by the Unicode loci of the characters in the converted string. For example, “Banana” will be placed before “cherry”. When numbers are sorted from smallest to largest, 9 appears before 80, but because (no compareFunction is specified) the comparison number is converted to a string first, “80” precedes “9” in Unicode order.

If compareFunction is specified, the array is sorted by the value returned from calling the function. That is, a and B are the two elements to be compared:

  • If compareFunction(a, b) is less than 0, then A is placed before B;

  • If compareFunction(a, b) is equal to 0, the relative positions of a and B remain the same. Note: The ECMAScript standard does not guarantee this behavior, and not all browsers comply (Mozilla prior to 2003, for example);

  • If compareFunction(a, b) is greater than 0, b will be placed before A.

  • CompareFunction (a, b) must always return the same comparison result on the same input, otherwise the sorting result will be indeterminate.

Therefore, the format of the comparison function is as follows:

Function compare(a, b) {if (a < b) {return -1; } if (a > b ) { return 1; } // a must be equal to b return 0; }Copy the code

To compare numbers instead of strings, the comparison function can simply be a minus b, and the following function will sort the array in ascending order

function compareNumbers(a, b) {
  return a - b;
}
Copy the code

The sort method can be conveniently written using function expressions:

var numbers = [4, 2, 5, 1, 3]; numbers.sort(function(a, b) { return a - b; }); console.log(numbers); Var numbers = [4, 2, 5, 1, 3]; numbers.sort((a, b) => a - b); console.log(numbers); // [1, 2, 3, 4, 5]Copy the code

Objects can be sorted by an attribute:

var items = [
  { name: 'Edward'.value: 21 },
  { name: 'Sharpe'.value: 37 },
  { name: 'And'.value: 45 },
  { name: 'The'.value: -12 },
  { name: 'Magnetic' },
  { name: 'Zeros'.value: 37}];// sort by value
items.sort(function (a, b) {
  return (a.value - b.value)
});

// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});
Copy the code

8.5 case

8.5.1. Alphabetical ordering

Sort the default sort is alphabetical. If the first letter is the same, the second letter is compared, and so on.

/ / 1. The default sort (sort) alphabetical order var arr = [" za ", "zb", "a", "b", "xc", "xa"]. arr.sort(); console.log(arr); [" A ", "b", "XA "," XC ", "za", "zb"]Copy the code

8.5.2. Sort sort numbers

The arguments in sort() can be method functions that output results in ascending and descending order.

Var array = [100,10,50,800,320,34,53]; Array. sort(function(a,b){return b-a; }); console.log(array); // Run result: [800, 320, 100, 53, 50, 34, 10]Copy the code

** note: ** where a and b represent the elements of the array, if a-b represents the ascending order, if b-a represents the descending order.

8.5.3. Sorting array objects

The most important still is the object properties sort, as the background to our front end a lot of data and there is no ordering, we are generally sorted again, and the background data is often several layers, not like that in front of the simple is an array, this time with a sort of object attributes sorting

/ / 3. Object attributes sorting var obj = [{name: "Lucy", num: 400}, {name: "Nancy," num: 110}, {name: "maria", num: 200}]. obj.sort(compare("num")); console.log(obj); Function compare(property){return function(a,b){// value1-value2 ascending // value2-value1 descending var value1 = a[property]; var value2 = b[property]; return value1 - value2; / / ascending}} running results: [{name: "Nancy," num: 110}, {name: "maria", num: 200}, {name: "Lucy", num: 400}]Copy the code

** The argument in **compare() must be the attribute name of the object, and the object you want to compare must have this attribute name, otherwise it will error. The above is a personal summary, if there is any supplement will be released again