JavaScript array manipulation

Source: Internet
Author: User
Tags truncated javascript array

Continue my second "JavaScript Advanced Programming Third Edition", today's note is an array

I. Operation of arrays

1, the creation of the array:

var colors= new Array (); Create an array var colors = new Array (20); Create an array and specify the length var colors = new Array ("Red", "Blue", "green"); Create an array and assign a value

Airbnb's specification suggests that when creating arrays, it's best to omit the new operator, as follows:

Airbnb website: https://github.com/airbnb/javascript

//  Bad var New  //  goodvar items = [];

2. Access to elements of an array

var colors=["Red", "Blue", "Green"]alert (Colors[0]); Show the first item colors[2]= "BLACK";  Revise the third item colors[3]= "Brown"; Added item Fourth

1. Access by square brackets and indexed values

2, set the index value in the range of other values, you can replace the value of the specified position

3. If the index value exceeds the number of existing entries in the array, the array is automatically incremented to the length of the index value plus 1, such as the new fourth item in the code

3. Add elements to the array:

There are several ways to do this:

1. Push to add the element to the end of the array:

var colors=[];colors.push ("Red", "Blue"); Console.log (colors);   // [Red,blue]

2. The index value exceeds the number of existing entries in the array to add. Because the index value is calculated from 0, the length of the array is always 1 larger than the index value

var colors=["Red", "Blue", "green"];colors[colors.length]= "BLACK"; console.log (colors);   // ["Red", "Blue", "green", "Black"];

3, Unshift, adding elements to the front of the array

var colors=["Red", "Blue", "Green"];colors.unshift ("Black"); Console.log (colors);  ["Black", "Red", "Blue", "green"];

  

4, splice, you can specify the position to insert an arbitrary array of items. You need at least three parameters: the starting position, 0, and the item to insert. Of course, you can insert more than one item.

var arr = ["George", "John", "Thomas", "James", "Adrew", "Martin"];arr.splice (2,0, "William") Console.log (arr);  ["George", "John", "William", "Thomas", "James", "Adrew", "Martin");

4. Deletion and substitution of arrays

Delete the array:

1, Arrayobj.pop (); Removes the last element and returns the element value

2, Arrayobj.shift (); Removes the first element and returns the element value, and the elements in the array are automatically moved forward

3, Arrayobj.splice (start,length); Removes the specified number of length elements from start of the specified position, returning the removed element as an array

4. The length of the specified array is less than

var arr = ["George", "John", "William", "Thomas", "James", "Adrew", "Martin"];var deleteitem1=arr.pop (); Console.log (DELETEITEM1);  Martinconsole.log (arr);  ["George", "John", "William", "Thomas", "James", "Adrew"]var deleteitem2=arr.shift (); Console.log (DELETEITEM2);  Georgeconsole.log (arr);   ["John", "William", "Thomas", "James", "Adrew"]var deleteitem3=arr.splice (0,2); Console.log (DELETEITEM3);  ["John", "William"]console.log (arr);          ["Thomas", "James", "Adrew"]arr.length=2;console.log (arr);  ["Thomas", "James"]

  

Substitution of arrays:

Array.splice (start,length, "Othervalue") passes three values, starts replacing positions, replaces the number, and replaces the value.

var arr = ["George", "John", "William", "Thomas", "James", "Adrew", "Martin"];var arr2 = ["George", "John", "William", " Thomas "," James "," Adrew "," Martin "];var deleteitem=arr.splice (0,1," 123 ");  Returns the substituted value Console.log (DeleteItem); ["George"]console.log (arr);  ["123", "William", "Thomas", "James", "Adrew", "Martin"]var deleteitem2=arr2.splice (0,2, "123", "456");  Returns the value that is replaced. Multiple values can be substituted console.log (DELETEITEM2); ["George", "John"]console.log (ARR2);  ["123", "456", "William", "Thomas", "James", "Adrew", "Martin")

5. Interception, merging and copying of arrays

1. Intercept array:slice (start,end)

Returns the truncated part as an array. Does not include the item for end.

If End is omitted, all elements after start are truncated.

Only 0, which is equivalent to copying an array

  

var arr = ["George", "John", "William", "Thomas", "James", "Adrew", "Martin"];var getarray=arr.slice (1,3); Console.log ( GetArray); ["John", "William"]console.log (arr);    ["George", "John", "William", "Thomas", "James", "Adrew", "Martin"  ) do not affect the original array var getarray2=arr.slice (1); Console.log (getArray2);  ["John", "William", "Thomas", "James", "Adrew", "Martin"]console.log (arr.slice (0)); ["George", "John", "William", "Thomas", "James", "Adrew", "Martin")

2. Merging of arrays:arrayobj.concat ([item1[, item2[, ... [, Itemn]]]); 

Concatenate multiple arrays (which can also be strings, or a mixture of arrays and strings) into an array, returning a new concatenated array.

If nothing is passed, it is equivalent to copying an array.

var arr = ["George", "John", "William", "Thomas", "James", "Adrew", "Martin"];var arr2=["123", "456"];var Arr3=arr.concat ( ARR2); Console.log (ARR3); ["George", "John", "William", "Thomas", "James", "Adrew", "Martin", "123", "456"]

 

 

6, the character of the array Fu Guahua: Array.join ();

Returns a string that connects each element value of an array, separated by an incoming value.

var arr = ["George", "John", "William", "Thomas", "James", "Adrew", "Martin"];console.log (Arr.join (', '));  George,john,william,thomas,james,adrew,martinconsole.log (Arr.join ('-')); George-john-william-thomas-james-adrew-martinconsole.log (Arr.join (")); George John William Thomas James adrew Martin

 

7. Ordering of arrays: reverse () reverse order sort () positive order

var arr = [1,5,8,9,6,3];console.log (Arr.reverse ());   [3, 6, 9, 8, 5, 1]console.log (Arr.sort ());  [1, 3, 5, 6, 8, 9]console.log (Arr.sort (). reverse ()); [9, 8, 6, 5, 3, 1]

  

 

second, advanced usage of arrays

1. Stack method and queue:

Stack method:

The stack is a LIFO (Last-in-first-out, LIFO) data structure, where the most recently added item is first removed. The insertion of the item in the stack (called Push-in) and the removal (called popup) occur only in one place-the top of the stack.

The ECMAScript provides the push () and Pop () methods specifically for implementing a stack-like behavior

var colors = ["Red", "Blue"];colors.push ("Brown"); Add another item colors[3] = "BLACK"; Add an alert (colors.length); 4var item = Colors.pop (); Get the last alert (item); "Black"

Queue method:

The access rules for queue data structures are FIFO (first-in-first-out, first-in, in-advance).

The queue adds items at the end of the list, removing items from the front end of the list. Using the shift () and push () methods together, you can use arrays as you would with queues.

var colors = new Array (); Create an array of var count = Colors.push ("Red", "green"); Push in two alert (count); 2count = Colors.push ("Black"); Push into another alert (count); 3var item = Colors.shift (); Get the first alert (item); "Red" alert (colors.length); 2

Stack method: Queue method:

2, the weight of the array

This is a problem that is often encountered in practical applications and in interviews. Therefore, we offer several solutions as follows:

Before introducing the method of IndexOf, first understand the method of the array, because the following will be used.

The IndexOf () method returns the position of the first element found in the array, or 1 if it does not exist.

var a = [' Red ', ' blue ', ' green ', ' Blue '];console.log (A.indexof ("Blue"));  1console.log (A.indexof ("Black"));  -1

  

Method 1: iterate through the array method

function unique (array) {var n = []; for (var i = 0; i < Array.Length; i++) {//If the current array of I has been saved into a temporary array, skip,//Otherwise push the current item to the temporary array Inside if (N.indexof (array[i]) = =-1) {N.push (array[i]);}} return n;} var testarry=[1,2,5,5,6];console.log (Unique (Testarry));  [1, 2, 5, 6]

Method 1 Cons: IE8 and IE8 below do not support indexOf

Method 2: object Key-value pair method

function unique (array) {var n = {};var r = [];var len = Array.length;var Val;var type;for (var i = 0; i < array.length; i++) {     val = array[i];     Type = typeof Val;     if (!n[val]) {         N[val] = [Type];                 R.push (val);     } else if (N[val].indexof (type) < 0) {         n[val].push (type);         R.push (val);     } } return R; }var testarry=["Hello", 2,5,5,6, "Hello"];console.log (Unique (Testarry));  ["Hello", 2, 5, 6]

  

More difficult to understand, a little explanation:

New JS object and new array, when traversing the incoming array, determine whether the value is the key of the JS object, not to add the key to the object and put into the new array.

You can look at what N returns: Object {2: ["number"], 5:["#"], 6: ["#"], "Hello: [" string "]}, let the value in the array be the key of the object, and let its value have only one array

Method 2 Advantages and disadvantages: the fastest speed. Cons: Occupies the most space (space change time)

Method 3: Array subscript judgment method

function unique (array) {var n = [array[0]];////result array//start with the second entry for (var i = 1; i < Array.Length; i++) {//If the current array of item I is the first in the current array The position of the second occurrence is not I,//Then the term I is repeated and ignored. Otherwise deposit the result array if (Array.indexof (array[i]) = = i) {N.push (array[i]);}} return n;} var testarry=["Hello", 2,5,5,6, "Hello"];console.log (Unique (Testarry));  ["Hello", 2, 5, 6]

Similar to Method 1, the array is not duplicated and then returned

Method 4: Sort the incoming array, sort the same values next to each other, and then iterate through the array to add only values that do not duplicate the previous value.

function unique (array) {//by Array.Sort (), Var re=[array[0]];for (var i = 1; i < Array.Length; i++) {if (Array[i]!== Re[re.length-1]) {   re.push (array[i]);}} return re;} var testarry=["Hello", 2,5,5,6, "Hello"];console.log (Unique (Testarry));  [2, 5, 6, "Hello"]

5. Optimized traversal Array method

Implementation idea: Gets the right-most value that is not duplicated into the new array. (The next round of judgment that terminates the current loop and enters the top loop when a duplicate value is detected)

function unique (array) {var r = [];for (var i = 0, L = array.length; i < L; i++) {for (var j = i + 1; j < L; j + +) {    if (array[i] = = = Array[j]) {   j = ++i   }}r.push (Array[i]);} return r;} var testarry=["Hello", 2,5,5,6, "Hello"];console.log (Unique (Testarry));  [2, 5, 6, "Hello"]

 

Method 6, simple method, similar to Method 1.

function unique (array) {  var arr=[];  var obj={};  for (Var i=0;i<array.length;i++) {    if (!obj[array[i]]) {      obj[array[i]]=array[i];      Arr.push (Array[i]);    }  }  return arr;}  var testarry=["Hello", 2,5,5,6, "Hello"]; Console.log (Unique (Testarry));  ["Hello", 2, 5, 6]

Because the simple, is also my favorite use, haha

  

3. Iterative Method

ECMASCRIPT5 defines 5 iterative methods for an array.

1. ForEach iterates through the array one item at a time in a set

You can use three parameters: Array object, element index, and array itself

var testarry=["Hello", 2,5,6];testarry.foreach (function (item, index, array) {  Console.log (item);//hello 2 5 6  Console.log (index); 0 1 2 3  console.log (array);//["Hello", 2,5,6]  output 4 times});

 

2, every () returns a Boolean value ( true or false ), determines whether each array item conforms to the specified function's condition, conforms to true , and vice versa.false

var Testarry=[10,8,5,6];var isBiggerThan7 = testarry.every (function (Ele,index,arr) {     return (ele >= 7);}); if (isBiggerThan7) {    console.log (' is greater than or equal to 7 '),} else {    console.log (' Not all greater than or equal to 7 ');} Not all are greater than or equal to 7

  

3, some () returns a Boolean value ( true or false) that determines whether each array item conforms to the condition of the specified function, and returns if any of the items are returned as truetrue

var Testarry=[10,8,5,6];var isBiggerThan7 = testarry.some (function (Ele,index,arr) {       return (ele >= 7);}); if (isBiggerThan7) {    Console.log (' has an element greater than or equal to 7 ');} else {    console.log (' no element greater than or equal to 7 ');} There are elements greater than or equal to 7

  

4 filter() : Each array item invokes the specified function, and the condition is true returned to a new array. Equivalent to filtering the contents of an array

var Testarry=[10,8,5,6];var BiggerThan7 = Testarry.filter (function (Ele,index,arr) {    if (ele >= 7) {        return true;    }); Console.log (BIGGERTHAN7);   [10, 8]

5, Map () each array item invokes the specified function, and returns the result of each function call to form a new array

Usage is basically the same as foreach, but there is a difference, foreach has no return value, and map has a return value

var Testarry=[10,8,5,6];var newArry1 = Testarry.map (function (Ele,index,arr) {    if (ele >= 7) {        return true;    }} ); Console.log (BiggerThan7);   [True, True, undefined, undefined]//--------------------------------------------------------------------------- --var NewArry2 = Testarry.foreach (function (Ele,index,arr) {    if (ele >= 7) {        return true;    }}); Console.log (NewArry2);   Undefined

  

4. Merge Method

ECMAScript5 has 2 methods for merging arrays: reduce () and reduceright ().

1, reduce (): From the first start one by one to traverse to the last. It receives two parameters Array.reduce (callback, InitialValue),

The callback function accepts 4 parameters: the previous value, the current value, the index value, and the array itself.

InitialValue Optional, which represents the initial value. If specified, it is treated as the originally used previous value, and if default, the first element of the array is used as the previous initial value and the back current row is a

(InitialValue's usage is not very clear.) Welcome Supplement )

var testarry=[10,8,5,6]; var result = Testarry.reduce (function(previous, current, index, array) {            return previous+ current;}); Console.log (result);    //  in

2, Reduceright (): Starts with the last item in the array and iterates to the first item in the array.

The usage is basically the same as reduce, but the starting position starts from the right first, the difference is just that.

var testarry=[10,8,5,6];var initialvalue=10;var result = testarry.reduceright (function (Previous, current, index, array ) {          return previous+current;}); Console.log (result);   29

  

third, es6 new array method

1, Array.from ()

The Array.from method is used to convert two types of objects into real arrays: arrays-like objects (Array-like object) and objects that can traverse (iterable) (including ES6 new data structure set and map).

The following three points need to be noted:


1. Any object with a length property can be converted to an array by means of the Array.from method.


2, the parameter is a class array object is similar to the array structure of the object, such as the key value is a number ah what


3, Array.from is the key as subscript and reference the Length property size to fill the element. The undefined complement is inserted when no suitable element is inserted.

Directly on the code:

varA = Array.from (' Hello ')); Console.log (a);//[' H ', ' e ', ' l ', ' l ', ' O ']//without passing length, the result returns an empty array, verifying the first point of attentionvarobj={"name": "Salted Fish", "Age": "$", "sex": "Male"}console.log (Array.from (obj)); //[]//there is a pass length, but not an array of classes, returning three undefined, validating the second, third note pointvarobj2={"name": "Salted Fish", "age": "the", "Sex": "Male", Length:3};console.log (Array.from (OBJ2)); //[Undefined, undefined, undefined]//there is a pass length, and the object is an array of classesvarobj3={"0": "Salted Fish", "1": "24", "2": "Male", Length:3}console.log (Array.from (OBJ3)); //["Salted Fish", "24", "Male"]//The key value does not start from 0, which verifies the attention point 3varObj4 = {"1": "Salted Fish", "2": "24", "3": "Male", Length:3};console.log (Array.from (OBJ4)); //[Undefined, "salted fish", "$"]

2, Array.of ();

The Array.of method is used to convert a set of values into an array

var a=array.of (3,9,10);  var b=array.of (3);  Console.log (a);  [3, 9, 10]console.log (b);  [3]console.log (b.length);  1

What is the difference between a normal array and a normal array? A new array of parameters is returned only if the number of arguments is not less than 2. When there is only one parameter number, it is actually the length of the specified array.

The following is an ordinary array, you can see the difference between the parameters only one:

var a=array (3,9,10);  var b=array (3);  Console.log (a);  [3, 9, 10]console.log (b);  [,,,]console.log (b.length);  3

  

 

3. Find () and FindIndex ()

The Find method of an array instance, which is used to find the first qualifying array member, whose argument is a callback function, in which all array members execute the callback function sequentially until they find the first member to return a value of true, and then return the member. If there are no eligible members, the undefined is returned.

The FindIndex method of an array instance is used very similarly to the Find method, returning the position of the first qualifying array member, or 1 if all members do not meet the criteria. Similar to indexOf ();  
var array=[3, 9, 10,15,6,20];//Findvar fn=array.find (function (Value,index,arr) {return value>10;}); Console.log (FN);  When this value is found, it will stop looking for Var fn2=array.find (function (Value,index,arr) {return value>30;}); Console.log (FN2);  undefined//-----------------------------------------------------------------//Findindexvar fn3= Array.findIndex (function (Value,index,arr) {return value>10;}); Console.log (FN3);  3  var fn4=array.findindex (function (Value,index,arr) {return value>30;}); Console.log (FN4);  

  

4. Fill ()

The fill method fills an array with the given value, and the Fill method can also accept the second and third parameters to specify the starting and ending positions of the fill
var array=[' A ', ' B ', ' C '];array.fill (7); Console.log (array);  [7, 7, 7]var array2=[' A ', ' B ', ' C ', ' d ', ' E '];array2.fill (7,1,3); Insert the 7console.log (array2) at the position labeled 1 and 2;  ["A", 7, 7, "D", "E"]

  

Mistake, please state

If you think the article is useful, you can also give a small red packet to encourage encouragement, haha

JavaScript array manipulation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.