Array operation in js

Keywords: Programming encoding Attribute less

Array API

  • API: Application Programming Interface;
  • The methods provided by objects in js are called API s;


Detect whether an object is an array; (used against complex data types;)
//Simple data type of;
A instanceof B / / is a made by B;
    var arr = [1,2,3];
    console.log(arr instanceof Array); //arr is not of type Array;

Array.isArray( )

Array.isArray(parameter); // Judge whether the parameter is an array and return a Boolean value;
    var arr = [1,2,3];
    var num = 123;
    console.log(Array.isArray(arr)); //true
    console.log(Array.isArray(num)); //false

toString( )

array.toString(); // Change the array into a string, remove [], and link the contents with commas;
    var arr = ["aaa","bbb","ccc"];
    console.log(arr.toString());      //Back to aaa,bbb,ccc

valueOf( )

array.valueOf();  //Returns the array itself;   
    var arr = ["aaa","bbb","ccc"];
    console.log(arr.valueOf());      //Returns the array itself  ["aaa","bbb","ccc"]

Array. Join (parameter)

array.join(parameter);  // The elements in the array can be linked into a string according to the parameters;
console.log(arr.join());    //As with toString(), link with comma
console.log(arr.join("|")); //Linking with parameters
console.log(arr.join("&")); //Linking with parameters
console.log(arr.join(" ")); //If it's a space, really use a space link
console.log(arr.join(""));  //Empty characters are seamless

Addition and deletion of array elements

push() and pop()

1. array.push() //Add elements at the end of the array;
2. array.pop()  //No parameters required; delete an item at the end of the array;
    var arr = [1,2,3];
    var aaa = arr.push("abc");//Add an element at the end of the array;
    console.log(arr);//Element has been modified
    console.log(aaa);//The return value is the length of the array;

    aaa = arr.pop();//No parameters required; delete an item at the end of the array;
    console.log(arr);//Element has been modified
    console.log(aaa);//The item deleted

unshift() and shift()

1. array.unshift() //Add an element at the front of the array;
2. array.shift()  //No parameters are required; delete an item at the front of the array;
    var arr = [1,2,3];
    aaa = arr.unshift("abc");//Add an element at the front of the array;
    console.log(arr);//Element has been modified
    console.log(aaa);//The return value is the length of the array;

    aaa = arr.shift();//No parameters are required; delete an item at the front of the array;
    console.log(arr);//Element has been modified
    console.log(aaa);//The item deleted

Array element sorting

reverse( )

reverse()   //Flip array
    var arr1 = [1,2,3,4,5];
    var aaa = arr1.reverse(); // [5,4,3,2,1]

sort( )

sort() // Sort the elements in the array; (default: from small to large)
      //  Default: sort by Unicode encoding of the first character; compare the second if the first is the same
    var arr = [4,5,1,3,2,7,6];
    var aaa =arr.sort();
    console.log(aaa);          // [1, 2, 3, 4, 5, 6, 7]
    console.log(aaa === arr);// true the original array is sorted (bubble sort)
    //Letters can also be arranged by default;
    var arr2 = ["c","e","d","a","b"];
    var bbb = arr2.sort();
    console.log(bbb);         // ["a", "b", "c", "d", "e"]
    console.log(bbb===arr2); // true the original array is sorted (bubble sort)

sort() //The sorting method of numerical value size needs the help of callback function;
      var arr = [4,5,1,13,2,7,6];
      //If the return value in the callback function is: parameter 1 - parameter 2; ascending power; parameter 2 - parameter 1; descending power;
      arr.sort(function (a,b) {
        return a-b; //Ascending order
        //return b-a; / / descending
        //return b.value-a.value; / / sorted by the size of the value attribute of the element;
      console.log(arr); // [1, 2, 4, 5, 6, 7, 13]

sort() underlying principle

    var aaa = bubbleSort([1,12,3], function (a,b) {
//        return a-b; / / argument: array[j]-array[j+1];
        return b-a;//Actual parameter: array[j+1]-array[j];

    function bubbleSort(array,fn){
        //The number of external control rounds and internal control rounds are all element numbers - 1;
        for(var i=0;i<array.length-1;i++){
            for(var j=0;j<array.length-1-i;j++){//Optimization of times, more than one round, less than one;
                //Meet the condition exchange position;
//                If (array [J] > array [J + 1]) {/ / is greater than ascending order; otherwise, descending order;
                //A-B > 0 and a > b are the same meaning;
                //B-A > 0 and a < B are the same meaning;
//                If (array [J] - array [J + 1] > 0) {/ / sort by ascending power
//                If (array[j+1]-array[j]>0) {/ / descending order
                //Send two variables to a function;
                    var temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
        //Return array
        return array;

Operation of array elements

concat( )

array1.concat(array2); // Link two arrays;
var arr1 = [1,2,3];
var arr2 = ["a","b","c"];
var arr3 = arr1.concat(arr2);
console.log(arr3)   //    [1, 2, 3, "a", "b", "c"]

slice( )

Array. Slice (start index value, end index value); / / array truncation;
For example:
      var arr = [1, 2, 3, "a", "b", "c"];
      console.log(arr.slice(3)); / / intercept from index value 3 to the end; ["a", "b", "c"]
      console.log(arr.slice(0,3)); / / left package does not include right package; [1,2,3]
      console.log(arr.slice(-2)); / / the negative number is the last; ["b", "c"]
      console.log(arr.slice(3,0)); / / if the former is larger than the latter, it is []; []
      console.log(arr); / / the original array is not modified; [1, 2, 3, "a", "b", "c"]

splice( )

array.splice(Start index value, delete several, replace content1,replace content2,...);  // Replace and delete;
                                                      //Change the original array;The return value is deleted/What to replace
    var arr = [1,2,3,4,5,6,"a", "b", "c"]
    arr.splice(5);        //From index value to3Intercept to the end;(delete)
    console.log(arr);     // [1, 2, 3, 4, 5]
    arr.splice(1,2);    //(Delete the specified number)From index to1Start deletion of2individual
    console.log(arr);   //[1, 4, 5]

    var arr = [1,2,3,4,5,6,"a", "b", "c"];
    console.log(arr.splice(3,3,"aaa","bbb","ccc"));    //(Delete specified number and replace)
    console.log(arr);     // [1, 2, 3, "aaa", "bbb", "ccc", "a", "b", "c"]
//    Add to
    arr.splice(3,0,"aaa","bbb","ccc");//(Delete the specified number)
    console.log(arr);//After interception or replacement;   [1, 2, 3, "aaa", "bbb", "ccc", "aaa", "bbb", "ccc", "a", "b", "c"]

indexOf / lastIndexOf

array.indexOf(element);      // Give element, look up index (from front to back)
//Array. LastIndexOf (element);  // To index (back to front) an element
    var arr = ["a","b","c","d","c","b","b"];
    console.log(arr.indexOf("b"));        // 1. Return immediately after finding out
    console.log(arr.lastIndexOf("b"));    // 6 return as soon as you find it
    console.log(arr.indexOf("xxx"));    // -1. Return - 1 if not found;

Array iteration (traversal)


Run the callback function for each item in the array, if it returnstrue,every Returntrue,
//If there is one returnfalse,Stop traversing every Returnfalse;Do not write default returnfalse
//Like a bodyguard mistake, the game is over!!!
1.    var arr = [111,222,333,444,555];
    arr.every(function (a,b,c) {
        console.log(a);    //element
        console.log(b);    //Index value
        console.log(c);    //Array itself;
        console.log("-----");    //Array itself;
        //Assignment of elements in the array: c[b] = value; a = sometimes assignment is impossible;
        return true;

2.  //every returns a bool value, all true is true; one is false, and the result is false
    var bool = arr.every(function (element, index, array) {
        //Judgment: we define that all elements are greater than 200;
        //if(element > 100){
        if(element > 200){
            return true;
            return false;
    alert(bool); //false


//   Run a callback function on each item in the array, which returns a new array of items with a result of true
//     The new array is composed of elements in the old array, and the return is the item of ture;
    var arr = [111,222,333,444,555];
    var newArr = arr.filter(function (element, index, array) {
        //As long as it's odd, it's an array
        if(element%2 === 0){
            return true;
            return false;

    console.log(newArr); // [222, 444]


// Same as for loop; no return value;
    var arr = [111,222,333,444,555];
    var sum = 0;
    var aaa = arr.forEach(function (element,index,array) {
        console.log(element); // Output every element in the array
        console.log(index); // Index value of array element
        console.log(array); // Array itself [111, 222, 333, 444, 555]
        sum += element; //Sum the elements in the array;
    console.log(sum); // Sum of array elements
    console.log(aaa);//Undefined; no return value so undefined


//  Run a callback function on each item in the array to return a new array composed of the results of the function
//    Return what is in the new array; do not return undefined; rework the array
    var arr = [111,222,333,444,555];
    var newArr = (element, index, array) {
        if(index == 2){
            return element; // The return value here is 333
        return element*100; // All returned element values are multiplied by 100
    console.log(newArr); // [11100, 22200, 333, 44400, 55500]


//Run a callback function for each item in the array. If the function returns true for a certain item, then some returns true. Like a killer, if one succeeds, it wins!!!
    var arr = [111,222,333,444,555];
    var bool = arr.some(function (ele,i,array) {
        //Judge: there are multiple of 3 in the array
        if(ele%3 == 0){
            return true;
        return false;
    alert(bool); //True; one success is true

Empty array

    1. arr.length = 0; // (bad, pseudo array cannot be emptied)
    2. arr.splice(0); // Pseudo array does not have this method;
    3. arr = [];     // Pseudo arrays can be manipulated; (recommended!)

// Pseudo array: it is long like an array, but there is no array method, and elements cannot be added or deleted;
//Example: // arguments
        function fn(){
            arguments.length = 0; // Cannot empty return [1, 2, 3]
           arguments.splice(0); // arguments.splice is not a function
            arguments = []; // Can be cleared, return empty array [] 

Array case

1.Output an array of strings as|The form of division, such as "Liu Bei|Zhang Fei|Guan Yu. Implemented in two ways

       var arr = ["Liu Bei","Zhang Fei","Guan Yu"];
       var separator = "|";
       //Accumulate by for loop
       var str = arr[0];
       for(var i=1;i<arr.length;i++){
           str += separator+arr[i];
       console.log(str); // Liu Bei, Zhang Fei, Guan Yu
       //join() can link elements in an array into a string;
       console.log(arr.join("|")); // Liu Bei, Zhang Fei, Guan Yu
2.Reverses the order of the elements of an array of strings.["a", "b", "c", "d"] -> [ "d","c","b","a"]. It can be realized in two ways. Tip: No i And length-i-1Exchange

  // Array. reverse() method
           var arr = ["a", "b", "c", "d"];
           console.log(arr.reverse()); // ["d", "c", "b", "a"]

       //  Three kinds: 1. Forward traversal, reverse add; 2. Reverse traversal, forward add; 3. Element exchange location of meta array;
           for(var i=0;i<arr.length/2;i++){
               var temp = arr[i];
               arr[i] = arr[arr.length-1-i];
               arr[arr.length-1-i] = temp;
3.Array of wages[1500, 1200, 2000, 2100, 1800],Pay more than2000Delete of

   var arr = [1500, 1200, 2000, 2100, 1800];
   //Use filter() to form an array; return true; an array;
   var newArr = arr.filter(function (ele, i, array) {
       //Return false if it is more than 2000;
           return true;
           return false;
   console.log(newArr); // [1500, 1200, 1800]
4.["c", "a", "z", "a", "x", "a"]Find each of the arrays a Where it appears

   var arr = ["c", "a", "z", "a", "x", "a"];
   //Traversal array (for / while / do... While) foreach();
   arr.forEach(function (ele, index, array) {
       //If the element is equal to "a", the index value is output;
       if("a" === ele){
5.Write a method to remove the duplicate elements of an array (Array de duplication)

       var arr = ["Naruto","Naruto","Sasuke","Sasuke","Sakura","Sakura"];
   //  Method 1: Idea: define a new array, traverse the old array, judge, if there is no element of the old array in the new array, add, otherwise, do not add;
       var newArr = [];
       //Traverse old array
       arr.forEach(function (ele,index,array) {
           //Check the elements in the old array. If the new array exists, it will not be added. If it does not exist, it will be added;
           if(newArr.indexOf(ele) === -1){//Add if it doesn't exist; (go to the new array to find the element index value, if it is - 1, it doesn't exist.)
       console.log(newArr); // ["Naruto", "Sasuke", "Sakura"]

Posted by stitchmedia on Mon, 04 May 2020 22:35:56 -0700