preface

By combing through the array API, inductive sorting, you will find that JS data methods are not difficult to remember, let’s learn ~

Remember, don’t be afraid to see so many array methods in the directory, be sure to first look at the array native method comb, learn exactly what the array has, and then learn one by one, so that you will suddenly find that there are not many methods in the array ~ all can be used

Array native method combing

🔶 数组 判断方法Array.isArray()

🔶 array merge method: concat(), returns a concatenated array, does not affect the original array.

🔶 Array and string conversion methods: toString(), join(), where join() can specify a delimiter when converted to a string.

🔶 Array tail operations: pop() and push(), the push() method can take multiple arguments.

🔶 array header operations: shift() and unshift();

🔶 array reorder methods: reverse() and sort(); The sort() method can pass in a function to compare the two values. If the return value is positive, b will be sorted before A. If the return value is negative, A will be sorted before B.

🔶 slice(), used to slice a portion of an array, returns a new array object that does not affect the original array. Arr. slice(begin, end). Slice extracts all elements indexed from begin to end (including begin, but not end). Note that the ❗ ❗ ❗ slice() method is a shallow copy, as explained below.

🔶 Array delete, replace, or insert method: splice(), which modifies an array by deleting or replacing existing elements or adding new ones in place, and returns the modified contents as an array (note not the entire array). This method changes the original array.

🔶 Array element lookup methods: indexOf(), includes(), find(), and findIndex()

🔶 array iteration methods: forEach(), map(), filter(), every(), and some()

🔶 array merge method: reduce()

🔶 array flat method: flat()

Array.isArray()An array of judgment

Array.isArray()Used to determine whether the value passed is an Array.

Array.isArray([1.2.3]);
// true
Array.isArray({foo: 123});
// false
Array.isArray("foobar");
// false
Array.isArray(undefined);
// false
Copy the code

🔶 instanceof and isArray

When detecting Array instances, array. isArray is superior to instanceof because array. isArray can detect iframes.

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1.2.3); / / [1, 2, 3]

// Correctly checking for Array
Array.isArray(arr);  // true
// Considered harmful, because doesn't work though iframes
arr instanceof Array; // false
Copy the code

concat()An array of merger

concat()The merge () method is used to merge two or more arrays. This method does not change an existing array, but returns a new array.

Merge two arrays:

const array1 = ['a'.'b'.'c'];
const array2 = ['d'.'e'.'f'];
const array3 = array1.concat(array2);

console.log(array3);// Array ["a", "b", "c", "d", "e", "f"]
Copy the code

Merge three arrays

The following code merges three arrays into a new array:

var num1 = [1.2.3],
    num2 = [4.5.6],
    num3 = [7.8.9];

var nums = num1.concat(num2, num3);

console.log(nums);// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

join()Array and string conversion

join()Method converts an array to a string and specifies a delimiter between all elements.

const elements = ['Fire'.'Air'.'Water'];

console.log(elements.join()); // "Fire,Air,Water"

console.log(elements.join(' ')); // "FireAirWater"

console.log(elements.join(The '-')); // "Fire-Air-Water"
Copy the code

Array tail operation

🍅 pop()

pop()Method removes the last element of the array and returns the value of that element. This method changes the length of the array.

const plants = ['broccoli'.'cauliflower'.'cabbage'.'kale'.'tomato'];

console.log(plants.pop()); // "tomato"

console.log(plants); // Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants); //Array ["broccoli", "cauliflower", "cabbage"]
Copy the code

🍅 push()

push()Method adds one or more elements to the end of an array and returns the new length of the array.

const animals = ['pigs'.'goats'.'sheep'];

const count = animals.push('cows');
console.log(count); / / 4
console.log(animals); // Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens'.'cats'.'dogs');
console.log(animals); // Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
Copy the code

Array head operation

🍅 shift()

shift()The delete () method removes the first element of the array and returns the value of that element. This method changes the length of the array.

const array1 = [1.2.3];

const firstElement = array1.shift();

console.log(array1); // Array [2, 3]

console.log(firstElement); / / 1
Copy the code

🍅 unshift()

unshift()Method adds one or more elements to the beginning of an array and returns the new length of the array (this method modifies the original array).

const array1 = [1.2.3];

console.log(array1.unshift(4.5)); / / 5

console.log(array1); // Array [4, 5, 1, 2, 3]
Copy the code

Array reorder

🍅 reverse() [r ɪ ˈ v ɜ rs]

reverse()Method reverses the position of the elements in an array and returns the array. This method changes the original array.

let a = [1.2.3.4.5];
a.reverse();
console.log(a); // (5) [5, 4, 3, 2, 1]
Copy the code

🍅 sort()

sort()The array_sort () method passes a function to sort the elements of an array. If the value returned is positive, b will be sorted before A. If the return value is negative, A will be sorted before B.

If no sorting algorithm is specified, the element is sorted according to 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.

Use without specifying the sorting algorithm:

const months = ['March'.'Jan'.'Feb'.'Dec'];
months.sort();
console.log(months);// Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1.30.4.21.100000];
array1.sort();
console.log(array1);// Array [1, 100000, 21, 30, 4]
Copy the code

Specify the use of the sorting algorithm:

Numbers can be compared simply by writing:

var numbers = [4.2.5.1.3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers); // [1, 2, 3, 4, 5]It can also be written as:var numbers = [4.2.5.1.3];
numbers.sort((a, b) = > a - b);
console.log(numbers); // [1, 2, 3, 4, 5]
Copy the code

You can sort by an attribute of the object:

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)
});
console.log(items);/ / /
							{"name": "The"."value": -12},
							{"name": "Edward"."value": 21},
							{"name": "Sharpe"."value": 37},
							{"name": "And"."value": 45},
							{"name": "Magnetic"},
							{"name": "Zeros"."value": 37}]Copy the code

CompareFunction (a, b) must always return the same comparison on the same input, otherwise the sorting result will be indeterminate, such as the output of the comparison function above, sorting on the value property.

So, if we sort by an attribute of an object, we need to make sure that the attribute value of the object exists:

var items = [
	{name: 'Edward'.value: 21},
	{name: 'Sharpe'.value: 37},
	{name: 'And'.value: 45},
	{name: 'The'.value: -12},
	{name: 'Magnetic'.value: 100},
	{name: 'Zeros'.value: 37}];// sort by value
items.sort(function (a, b) {
    return (b.value - a.value)
    // Note that a. value-b. value is changed to b. value-a. value
    // In reverse order
});
console.log(items);/ / /
							{"name": "Magnetic"."value": 100},
							{"name": "And"."value": 45},
							{"name": "Sharpe"."value": 37},
							{"name": "Zeros"."value": 37},
							{"name": "Edward"."value": 21},
							{"name": "The"."value": -12}]Copy the code

slice() [sla ɪ s]Array interception ✨

slice()Intercepts a portion of an array and returns a new array object without affecting the original array.

Note ❗ ❗ ❗slice()The method is shallow copy, as explained below.

arr.slice(begin, end).sliceWill extract the original array index frombeginendAll elements of thebegin, but does not containend).

Begin Optionally extracts the original array elements from the index starting from 0.

  • If this parameter is negative, it extracts from the penultimate element of the original array, and slice(-2) extracts from the penultimate element of the original array to the last element, including the last element.

  • If begin is omitted, slice starts at index 0.

  • If BEGIN exceeds the index range of the original array, an empty array is returned.

End optionally extracts the index at the end (starting at 0), where the original array element is extracted. Slice extracts all elements indexed from begin to end (including begin, but not end).

  • Slice (1,4) extracts all elements (elements indexed 1, 2, and 3) from the second element through the fourth element in the array.

  • If this parameter is negative, it indicates the penultimate element in the original array at the end of the extraction. Slice (-2,-1) extracts the penultimate element of the array to the last element (excluding the last element, i.e. only the penultimate element).

  • If end is omitted, slice extracts all the way to the end of the original array.

  • If end is greater than the length of the array, Slice will extract all the way to the end of the array.

❗ ❗ ❗ slice()A shallow copy of the method

Slice does not modify the original array, but only returns a new array that copies elements in the original array. Elements of the original array are copied according to the following rules:

  • If the element is an object reference (not an actual object),sliceWill copy the object reference into the new array. Both object references refer to the same object. If the referenced object changes, the element in the new and original array changes as well.
  • For strings, numbers, and Booleans (not String, Number, or Boolean objects),sliceIt copies those values into a new array. Modifying these strings or numbers or booleans in another array will not affect the other array.

If you add a new element to either array, the other is unaffected.

Take a closer look at a shallow copy of the slice() method with an example:

The following code describes several cases of modifying an array:

let menuTreeList = [{
                "id": "cfda8029dfb311e7b555201a068c6482"."name": "System Management"."menuType": 0."children": [{
                    "id": "3873ccc2dfda11e7b555201a068c6483"."name": "Menu Management"."menuType": 2."children": [{
                            "id": "18bf8d5df09511e78a57201a068c6484"."name": "New"."menuType": 1
                        },
                        {
                            "id": "18bf8d5df09511e78a57201a068c6485"."name": "Change"."menuType": 1}}]}, {"id": "cfda8029dfb311e7b555201a068c6486"."name": "Equipment Management"."menuType": 0."children": [{
                        "id": "18bf8d5df09511e78a57201a068c6487"."name": "New"."menuType": 1
                    },
                    {
                        "id": "18bf8d5df09511e78a57201a068c6488"."name": "Change"."menuType": 1}}]]let a = menuTreeList.slice(0.1);
 console.group("1. Modify the deep properties of the object")
 // console.log('a :>> ', a);
 // 1. If the referenced object is changed, this element in the new and original array will also change:
 // Change the original value menuTreeList[0], that is, change the reference of the object
 menuTreeList[0].children = [];
 / / validation:
 // The original array:
 console.log('Modified original array menuTreeList :>>', menuTreeList);
 // The slice method generates a new array:
 console.log('New array A :>>', a);
 console.groupEnd()



 let newArr = [1.2.3.4.5.6];
 let b = newArr.slice(0.4);
 console.group(2. Validate array elements as strings, numbers, and Booleans)
 // console.log('b :>> ', b);
 // 2. Slice copies strings, numbers, and Booleans into a new array.
 // Changing these strings or numbers or booleans in another array will not affect the other array:
 newArr[0] = 0;
 newArr[1] = 0;
 newArr[2] = 0;
 newArr[3] = 0;
 // The original array:
 console.log('Modified original array newArr :>>', newArr);
 // The slice method generates a new array:
 console.log('New array B :>>', b);
 console.groupEnd();



 let newArr3 = [{
     "id": "1"."name": "Equipment Management"."menuType": 0}, {"id": "2"."name": "Equipment Management"."menuType": 0}, {"id": "3"."name": "Equipment Management"."menuType": 0}, {"id": "4"."name": "Equipment Management"."menuType": 0,}];let d = newArr3.slice(0.3);
 console.group("3. Modify property validation for simple objects")
 // console.log('d :>> ', d);
 newArr3[0].id = "111111111";
 newArr3[1].id = "111111111";
 newArr3[2].id = "111111111";
 // The original array:
 console.log('Modified original array newArr3 :>>', newArr3);
 // The slice method generates a new array:
 console.log('New array D :>>', d);
 console.groupEnd();



 let newArr2 = [{
     "id": "1"."name": "Equipment Management"."menuType": 0}, {"id": "2"."name": "Equipment Management"."menuType": 0}, {"id": "3"."name": "Equipment Management"."menuType": 0}, {"id": "4"."name": "Equipment Management"."menuType": 0,}];let c = newArr2.slice(0.3);
 console.group("4. Null array simple object validation")
 // console.log('c :>> ', c);
 newArr2[0] = {};
 newArr2[1] = {};
 newArr2[2] = {};
 // The original array:
 console.log('Modified original array newArr2 :>>', newArr2);
 // The slice method generates a new array:
 console.log('New array C :>>', c);
 console.groupEnd()



 let newArr4 = [{
     "id": "1"."name": "Equipment Management"."menuType": 0}, {"id": "2"."name": "Equipment Management"."menuType": 0}, {"id": "3"."name": "Equipment Management"."menuType": 0}, {"id": "4"."name": "Equipment Management"."menuType": 0,}];let e = newArr4.slice(0.3);
 console.group("5. Change the array simple object element to basic datatype validation")
 newArr4[0] = 0;
 newArr4[1] = 0;
 newArr4[2] = 0;
 // The original array:
 console.log('Modified original array newArr4 :>>', newArr4);
 // The slice method generates a new array:
 console.log('New array E :>>', e);
 console.groupEnd()
Copy the code

Output result: whyChange the array simple object elements to primitive data typesandEmpty the array simple objectIn both cases, the array doesn’t change, right?

I learned this question from CSDN blog expert “zero one”, bytedance big guy, many high quality original articles, come to visit 👉✨ “zero one” ✨👈

Problem analysis:

We can immediately say, [q, w, e], in fact, the first element in this array is the variable Q, so it refers to an object,

  • If you modify the properties inside the object, then the variable q still refers only to the object, and the memory address of the object remains the same
  • If you just change the first element of the array to an empty object, then it equalsq = {}That must point to something different

That is, the elements in the original array are replaced with new objects, with new object references, and the element objects in the new array are still stored in the heap, with the old object references.

Let’s look at the following example:

  let newArr6 = [{
      "id": "1"."name": "Equipment Management"."menuType": 0}, {"id": "2"."name": "Equipment Management"."menuType": 0}, {"id": "3"."name": "Equipment Management"."menuType": 0}, {"id": "4"."name": "Equipment Management"."menuType": 0,}];let f = newArr6.slice(0.3);
  console.group("6. Set array simple object as new object validation")
  // console.log('c :>> ', c);

  newArr6[0] = {
      "sss": "4444"."aaaa": "Is the other party?"}; newArr6[1] = {
      "sss": "4444"."aaaa": "Is the other party?",};; newArr6[2] = {
      "sss": "4444"."aaaa": "Is the other party?",};;// The original array:
  console.log('Modified original array newArr6 :>>', newArr6);
  // The slice method generates a new array:
  console.log('New array f :>>', f);
  console.groupEnd()
Copy the code

Output result: In fact, whether you change an object to a primitive data type, or assign a new object, they all belong to the same class, they all change the object pointing

Here’s a comparison with basic object reference assignment:

let menuTreeList = [{
         "id": "cfda8029dfb311e7b555201a068c6482"."name": "System Management"."menuType": 0."children": [{
             "id": "3873ccc2dfda11e7b555201a068c6483"."name": "Menu Management"."menuType": 2."children": [{
                     "id": "18bf8d5df09511e78a57201a068c6484"."name": "New"."menuType": 1
                 },
                 {
                     "id": "18bf8d5df09511e78a57201a068c6485"."name": "Change"."menuType": 1}}]}, {"id": "cfda8029dfb311e7b555201a068c6486"."name": "Equipment Management"."menuType": 0."children": [{
                 "id": "18bf8d5df09511e78a57201a068c6487"."name": "New"."menuType": 1
             },
             {
                 "id": "18bf8d5df09511e78a57201a068c6488"."name": "Change"."menuType": 1}}]]let a = menuTreeList;
 console.group("1. Modify the deep properties of the object")
 menuTreeList[0].children = [];
 / / validation:
 // The original array:
 console.log('Modified original array menuTreeList :>>', menuTreeList);
 console.log('New array A :>>', a);
 console.groupEnd()



 let newArr = [1.2.3.4.5.6];

 let b = newArr;
 console.group(2. Validate array elements as strings, numbers, and Booleans)
 newArr[0] = 0;
 newArr[1] = 0;
 newArr[2] = 0;
 newArr[3] = 0;

 // The original array:
 console.log('Modified original array newArr :>>', newArr);
 console.log('New array B :>>', b);
 console.groupEnd();



 let newArr3 = [{
     "id": "1"."name": "Equipment Management"."menuType": 0}, {"id": "2"."name": "Equipment Management"."menuType": 0}, {"id": "3"."name": "Equipment Management"."menuType": 0}, {"id": "4"."name": "Equipment Management"."menuType": 0,}];let d = newArr3;
 console.group("3. Modify property validation for simple objects")
 newArr3[0].id = "111111111";
 newArr3[1].id = "111111111";
 newArr3[2].id = "111111111";

 // The original array:
 console.log('Modified original array newArr3 :>>', newArr3);
 console.log('New array D :>>', d);
 console.groupEnd();

 let newArr2 = [{
     "id": "1"."name": "Equipment Management"."menuType": 0}, {"id": "2"."name": "Equipment Management"."menuType": 0}, {"id": "3"."name": "Equipment Management"."menuType": 0}, {"id": "4"."name": "Equipment Management"."menuType": 0,}];let c = newArr2;
 console.group("4. Null array simple object validation")
 newArr2[0] = {};
 newArr2[1] = {};
 newArr2[2] = {};

 // The original array:
 console.log('Modified original array newArr2 :>>', newArr2);
 console.log('New array C :>>', c);
 console.groupEnd()


 let newArr4 = [{
     "id": "1"."name": "Equipment Management"."menuType": 0}, {"id": "2"."name": "Equipment Management"."menuType": 0}, {"id": "3"."name": "Equipment Management"."menuType": 0}, {"id": "4"."name": "Equipment Management"."menuType": 0,}];let e = newArr4;
 console.group("5. Change the array simple object element to basic datatype validation")

 newArr4[0] = 0;
 newArr4[1] = 0;
 newArr4[2] = 0;

 // The original array:
 console.log('Modified original array newArr4 :>>', newArr4);
 console.log('New array E :>>', e);
 console.groupEnd()
Copy the code

splice() [spla ɪ s]Array deletion, replacement, or insertion

splice()Method modifies an array by removing or replacing existing elements or adding new ones in place, and returns the modified contents as an array. This method changes the original array.

Grammar:

array.splice(start, deleteCount, item1, item2, ...)
Copy the code

Start Specifies the starting position of the modification (counting from 0). If the length of the array is exceeded, the contents are appended from the end of the array. If it is negative, it represents the number of bits from the end of the array (counting from -1, which means -n is the NTH element to the last and equivalent to array.length-n); If the absolute value of a negative number is greater than the length of the array, the starting position is bit 0.

DeleteCount An optional integer representing the number of array elements to be removed.

  • ifdeleteCountIs greater thanstartThe total number of subsequent elements goes fromstartAll subsequent elements will be deleted (including the firststartA).
  • ifdeleteCountIs omitted, or its value is greater than or equal toarray.length - start(That is, if it is greater than or equal tostartThe number of all subsequent elements), thenstartThen all the elements of the array are deleted.
  • ifdeleteCount0Or negative, the element is not removed. In this case, at least one new element should be added.

item1, item2, … Optional elements to add to the array, starting at the start position. If not specified, splice() will delete only array elements.

An array of deleted elements. If only one element is removed, an array containing only one element is returned. If no element is deleted, an empty array is returned.

If the number of elements added to the array does not equal the number of elements removed, the length of the array changes accordingly.

Example:

🔶 array inserts elements, removing 0 elements from index 2, insert"Drum"

var myFish = ["angel"."clown"."mandarin"."sturgeon"];
var removed = myFish.splice(2.0."drum");

// myFish: ["angel", "Clown ", "drum", "mandarin"," Sturgeon "]
// Deleted element: [], no element is deleted
Copy the code

🔶 array removes elements, 1 element starting at index 3

var myFish = ['angel'.'clown'.'drum'.'mandarin'.'sturgeon'];
var removed = myFish.splice(3.1);

// myFish: ["angel", "Clown ", "drum"," Sturgeon "]
// Deleted element: ["mandarin"]
Copy the code

🔶 array replaces elements, starts deleting 1 element at index 2, and inserts “trumpet”

var myFish = ['angel'.'clown'.'drum'.'sturgeon'];
var removed = myFish.splice(2.1."trumpet");

// 运算后的 myFish: ["angel", "clown", "trumpet", "sturgeon"]
// Deleted element: ["drum"]
Copy the code

🔶 array replace elements, remove 2 elements from index 0, insert “parrot”, “anemone”, and “blue”

var myFish = ['angel'.'clown'.'trumpet'.'sturgeon'];
var removed = myFish.splice(0.2.'parrot'.'anemone'.'blue');

// myFish after calculation: [" Parrot ", "Anemone "," Blue ", "Trumpet "," Sturgeon "]
// Removed element: ["angel", "Clown "]
Copy the code

🔶 array removes all elements after an index, starting at index 2

var myFish = ['angel'.'clown'.'mandarin'.'sturgeon'];
var removed = myFish.splice(2);

// myFish: ["angel", "Clown "]
// Deleted element: ["mandarin", "sturgeon"]
Copy the code

Array finds the specified element

🍅 indexOf()

indexOf()Method returns the first index in the array where a given element can be found, or -1 if none exists.

indexOf()Use strict equality(Strict equality, ===)To comparesearchElementAnd the elements in the array.

Grammar:

arr.indexOf(searchElement, fromIndex)
Copy the code

SearchElement The element to find

FromIndex Optional starting position.

🔶 finds all the places where the specified element occurs(Note, all elements; an element may appear multiple times in an array.)

var indices = [];
var array = ['a'.'b'.'a'.'c'.'a'.'d'];
var element = 'a';
var idx = array.indexOf(element);
while(idx ! = -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
/ / [0, 2, 4]
Copy the code

🔶 can be used to determine if an element is in an array

🍅 lastIndexOf()

lastIndexOf()Method returns the index of the last element in the array, or -1 if none exists. Look forward from the back of the array, starting at fromIndex.

lastIndexOfUse strict equality(Strict equality, ===)To comparesearchElementAnd the elements in the array.

🍅 includes()

includes()The array () method checks whether an array contains a specified value, depending on the case, and returns if it doestrueOtherwise returnfalse.

const array1 = [1.2.3];

console.log(array1.includes(2));// true

const pets = ['cat'.'dog'.'bat'];

console.log(pets.includes('cat'));// true

console.log(pets.includes('at'));// false
Copy the code

🍅 find()

find()The callback method executes a callback function for each element in the array until there is onecallbackreturntrue. When such an element is found, the method willReturn the value of this element immediatelyOtherwise returnundefined.

const array1 = [5.12.8.130.44];

const found = array1.find(element= > element > 10);/ / 12
Copy the code

🔶 finds objects in an array using their properties

var inventory = [
    {name: 'apples'.quantity: 2},
    {name: 'bananas'.quantity: 0},
    {name: 'cherries'.quantity: 5}];function findCherries(fruit) {
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
Copy the code

🍅 findIndex()

findIndex()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.

const array1 = [5.12.8.130.44];

const isLargeNumber = (element) = > element > 13;

console.log(array1.findIndex(isLargeNumber));/ / 3
Copy the code

An array of iteration

🍅 forEach()

forEach()Method executes a given function once on each element of the array.

const array1 = ['a'.'b'.'c'];

array1.forEach(element= > console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"
Copy the code

🔶 converts the for loop to forEach

const items = ['item1'.'item2'.'item3'];
const copy = [];

// before
for (let i=0; i<items.length; i++) {
  copy.push(items[i]);
}

// after
items.forEach(function(item){
  copy.push(item);
});
Copy the code

🔶 flat array

The following examples are for learning purposes only. If you want to use built-in methods for flattening arrays, you can consider using array.prototype.flat () (expected to be part of ES2019 and already implemented in major browsers)

/**
 * Flattens passed array in one dimensional array
 *
 * @params {array} arr
 * @returns {array}* /
function flatten(arr) {
  const result = [];

  arr.forEach((i) = > {
    if (Array.isArray(i)) result.push(... flatten(i));else
      result.push(i);
  })

  return result;
}

// Usage
const problem = [1.2.3[4.5[6.7].8.9]];

flatten(problem); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

🍅 map()

map()Method creates a new array, which calls each element in the original array once in ordercallbackFunction. Returns the result of executing the callback function on each element of the original arrayThe new array.

const array1 = [1.4.9.16];

// pass a function to map
const map1 = array1.map(x= > x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]
Copy the code

🍅 filter()

filter()The callback method creates a new array, calls the callback function once for each element in the array, and makes all thecallbackreturntrueA value equivalent to trueElement to create aThe new array.

Filter does not alter the original array; it returns the filtered new array.

const words = ['spray'.'limit'.'elite'.'exuberant'.'destruction'.'present'];

const result = words.filter(word= > word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Copy the code

🔶 filter excludes all smaller values

function isBigEnough(element) {
  return element >= 10;
}
var filtered = [12.5.8.130.44].filter(isBigEnough);
// filtered is [12, 130, 44]
Copy the code

🍅 every()

every()Method tests whether all elements in an array pass the test of a specified function. It returns a Boolean value.

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

const isBelowThreshold = (currentValue) = > currentValue < 40;

const array1 = [1.30.39.29.10.13];

array1.every(isBelowThreshold) //true
Copy the code

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.

🔶 checks 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

🔶 use 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

🍅 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 you test with an empty array, it returns false in any case.

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.

🔶 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

🔶 uses 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

reduce()Array merge

Refer to this article: Take the maximum value of the array (ES5, ES6) and explain the math.max () and reduce() apis in detail

flat()Array flattening

The Flat () method recurses through the array of numbers at a specified depth and returns all the elements in a new array combined with the elements in the traversed subarray.

grammar

var newArray = arr.flat(depth)
Copy the code

Depth Optionally specifies the depth of the structure to extract the nested array. The default value is 1.

Returns a new array containing all the elements of the array and its subarrays.

🔶 flat nested array

var arr1 = [1.2[3.4]];
arr1.flat();
// [1, 2, 3, 4]

var arr2 = [1.2[3.4[5.6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1.2[3.4[5.6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
Copy the code

🔶 flatten and remove array empty entries

The flat() method removes empty items from the array:

var arr4 = [1.2.4.5];
arr4.flat();
// [1, 2, 4, 5]
Copy the code