Array flattening

Concept: Used to “flatten” an array of nested layers into a one-dimensional array

Method 1: Convert a two-dimensional array to a one-dimensional array using concat

How it works: Returns a new array by extending the operator, expanding the inside of the array, and concatenating two strings

 let a = [12.3.45[6.7.8]]
 console.log(a)   // [12, 3, 45, Array(3)]
 console.log([].concat(... a))// [12, 3, 45, 6, 7, 8]
Copy the code

Method 2: Use the array method join and string method split to flatten the array

Principle: Through the join method will be converted into a dot separated string, in the use of split converted string into string array, through. The map method converts the internal string to a numeric type

let a = [4.1.2.3.6[7.8[3.9.10[4.6.11]]]];
let b = a.join(', ').split(', ').map(Number)
console.log(b) // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, 4, 6, 11]
Copy the code

Method three: through the regular method and json. stringify method and array method

Principle: First convert array to string use string matching regular rule to replace all ‘[“]’ and method 2 similar split is mainly to convert string into array, map string array into numbers

let a = [4.1.2.3.6[7.8[3.9.10[4.6.11]]]];
let c = JSON.stringify(a).replace(/\[|\]/g.' ').split(', ').map(Number);
console.log(c) // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, 4, 6, 11]
Copy the code

Method 4: function recursion

Principle: Determine whether the current value is an array, if it is an array, recursive call

let d = [];
let fn = arr= > {
   for (let i = 0; i < arr.length; i++) {
     if (Array.isArray(arr[i])) {
         fn(arr[i]);
          } else {
            d.push(arr[i]);
          }
        }
     }
fn(a)
console.log(d) // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, 4, 6, 11]
Copy the code

Method 5: Use reduce to flatten the array

Principle: It is mainly through the sequential execution of reduce to determine whether the current object is an array or not. If it is an array, it will perform a recursive function to flatten all internal arrays (similar to method 4).

let a = [4.1.2.3.6[7.8[3.9.10[4.6.11]]]]; 
function flatten(arr) {
      return arr.reduce((result, item) = > {
          console.log(result, item); // If you look at the result, you will see that each array is split and extracted
          return result.concat(Array.isArray(item) ? flatten(item) : item); } []); };console.log(flatten(a)) // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, 4, 6, 11]
Copy the code

Method 6: ES6 added method Flat ()

let a = [4.1.2.3.6[7.8[3.9.10[4.6.11]]]]; 
let e = a.flat()   // The array is converted from a two-dimensional array to a one-dimensional array
console.log(e)     // [4, 1, 2, 3, 6, 7, 8, Array(4)]
let f = a.flat(2)  // Passing a 2 converts a two-layer nested array to a one-dimensional array
console.log(f)     // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, Array(3)]
let g = a.flat(Infinity) // Infinity uses this keyword to convert a contained so-called array to a one-dimensional array
console.log(g)     // [4, 1, 2, 3, 6, 7, 8, 3, 9, 10, 4, 6, 11]
Copy the code

Array to heavy

Concept: Remove duplicate values from an array

Method 1: cyclic traversal interception

Principle: By comparing the current value in the array each time through the loop, the current value is deleted and the index is decrement by one, which changes the original array

let arr = [1.23.1.1.1.3.23.5.6.7.9.9.8.5];
    function removeDuplicatedItem(arr) {
       for (var i = 0; i < arr.length - 1; i++) {
            for (var j = i + 1; j < arr.length; j++) {
              if (arr[i] === arr[j]) {
                  arr.splice(j, 1);//console.log(arr[j]);j--; }}}return arr;
    }
let arr2 = removeDuplicatedItem(arr);
console.log(arr);  // [1, 23, 3, 5, 6, 7, 9, 8]
console.log(arr2); // [1, 23, 3, 5, 6, 7, 9, 8]
Copy the code

Method 2: Use indexOf()

Principle: It is similar to method 1 to determine whether the index of the element’s first occurrence in the array is equal to the index of the loop

let arr = [1.23.1.1.1.3.23.5.6.7.9.9.8.5];
        function rep2(arr) {
            for (var i = 0; i < arr.length; i++) {
                // console.log(arr.indexOf(arr[i])); You can print the index of the first occurrence of the current element
                if(arr.indexOf(arr[i]) ! == i) { arr.splice(i,1);// The element after the array length is reduced by 1 moves forward
                    i--;// Array subscript rollback}}return arr;
        }
 let arr2 = rep2(arr);
 console.log(arr);  // [1, 23, 3, 5, 6, 7, 9, 8]
 console.log(arr2); // [1, 23, 3, 5, 6, 7, 9, 8]
Copy the code

Method 3: Use the new array and indexOf() methods

If the indexOf the current element in the array is equal to the indexOf the loop, add it to the new array

let  arr = [1.23.1.1.1.3.23.5.6.7.9.9.8.5];
       function rep(arr) {
           let ret = [];
           for (var i = 0; i < arr.length; i++) {
               if(arr.indexOf(arr[i]) == i) { ret.push(arr[i]); }}return ret;
      }
let arr2 = rep(arr);
console.log(arr);  // [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5]
console.log(arr2); // [1, 23, 3, 5, 6, 7, 9, 8]
Copy the code

Method 4: Use empty objects

Principle: Using objects to record the stored elements in the new array without changing the original array is similar to method 3

 let arr = [1.23.1.1.1.3.23.5.6.7.9.9.8.5];
 let o = {};
 let arr2 = [];
 for (var i = 0; i < arr.length; i++) {
     var k = arr[i];
     if(! o[k]) { o[k] =true; arr2.push(k); }}console.log(arr);  // [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5]
console.log(arr2); // [1, 23, 3, 5, 6, 7, 9, 8]
Copy the code

Method 5: Filter method

Principle: Search the current element index position is equal to the current element index value, is true returns, if the current element index is not equal to the current index, it has appeared, does not return. The original array is unchanged

let arr = [1.23.1.1.1.3.23.5.6.7.9.9.8.5];
let arr2 = arr.filter(function (element, index, array) {
            return array.indexOf(element) === index;
        });
console.log(arr);  // [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5]
console.log(arr2); // [1, 23, 3, 5, 6, 7, 9, 8]
Copy the code

Method 6: Use the include method

Similar to indexOf, this index checks whether the current element exists and does not alter the array if it does not exist

let arr = [1.23.1.1.1.3.23.5.6.7.9.9.8.5];
function rep() {
      let res = [];
      for (let i = 0; i < arr.length; i++) {
         if(! res.includes(arr[i])) res.push(arr[i]); }return res;
    }
console.log(arr);  // [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5]
console.log(rep()); // [1, 23, 3, 5, 6, 7, 9, 8]
Copy the code

Method 7: Es6 new data structure new Set() method

Principle: Members of a new Set() are unique and cannot be repeated

let arr = [1.23.1.1.1.3.23.5.6.7.9.9.8.5];
let arr2 = new Set(arr)
console.log(arr);  // [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5]
console.log(arr2)  // {1, 23, 3, 5, 6,... }
console.log(rep()); // [1, 23, 3, 5, 6, 7, 9, 8]
Copy the code

Do a qualified code porter, baidu, Baidu test, test again baidu.