Today is a special day, we programmers common holiday, 1024, I wish every programmer happy holiday!

Arrays are essential to javascript, and today let’s summarize some common ways to manipulate arrays.

Arrays and common methods in arrays

Arrays are object types, special objects

let ary = [12.23.34.45]
console.log(typeof Ary) // =>"object"
console.dir(ary)  // 1. Number as index (key attribute name) 2. Length as length


Copy the code

Common methods in arrays

  • The function and meaning of the method
  • Method arguments (type and meaning)
  • Method return value
  • Whether the original array has changed

1. Implement the method of adding, deleting and changing the array

This part of the method will modify the original array

push

Push: Add content to the end of the array @params multiple arbitrary types @return The length of the array after the addition

let ary = [10.20]
let res = ary.push(12.30)
console.log(res) / / 4
console.log(ary) // [10, 20, 12, 30
// Methods that operate on key-value pairs based on native JS can also append a new item to the end
ary[ary.length] = 40
console.log(ary)
Copy the code

unshift

Unshift: Adds content to the beginning of the array @params Multiple arbitrary types @return The length of the array after the addition

let ary = [10.20]
let res = ary.unshift(12.30)
console.log(res) / / 4
console.log(ary) // [10, 20, 12, 30]
// Clone the original ARY based on the native ES6 expansion operator, create the first item in the new array, the rest of the content using the original ARY information, also calculate
// Append to start
ary = [100. ary]console.log(ary)
Copy the code

shift

Shift: Deletes the first item in the array @params@return deletes the item

let ary = [10.20.12.30]
let res = ary.shift()
console.log(res, ary) // 10 [20, 12, 30]
Copy the code

Based on the delete in native JS, the array is treated as an ordinary object, which can indeed delete a certain content, but will not affect the structural characteristics of the array itself (the length length will not be changed). In real projects, such deletion can be eliminated by using POP

Pop: Removes the last item in the array @params

@return The item deleted

let ary = [10.20.30.40]
let res = ary.pop();
console.log(res, ary) // 40, [10, 20, 30]


Copy the code

Based on native JS, the array length is removed by one bit, and the last item is removed by default

let ary = [10.20.30.40]
ary.length--;
console.log(ary)
Copy the code


splice

Splice: Achieve an array of add, delete, modify @ params n, m are all digital, removed from the index n m elements (m don’t write, delete to the end) n, m, x, removed from the index n m elements, use x occupied delete part n, 0, x from the beginning of the index n, a don’t delete, Put x in front of index n. @return stores the deleted portion in a new array

let ary = [10.20.30.40]
let res = ary.splice(2.2)
console.log(res, ary)
// This method is used to empty an array and store the contents of the original array in the new array
//ary.splice(0)


// Delete the last and first items
ary.splice(ary.length-1)
ary.splice(0.1)
console.log(ary)

Append to the end of the array
ary.splice(ary.length,0.'aaa')

// Start appending to the array
ary.splice(0.0.'aaa')
Copy the code

2. Array query and concatenation

This group of methods, the original array does not change

slice

Slice: implement array query @params n, m are all numbers, starting with index n, find the index m (excluding m) @return returns the found contents as a new array

let ary = [10.20.30.40.50]
let res = ary.slice(1.3)
console.log(res, ary) [10, 20, 30, 40, 50]

// Array clone, parameter 0 can not write, shallow clone
let res2 = ary.slice(0)

Copy the code

concat

Slice: implement array concatenation @params multiple hot arbitrary type values @return concatenate new array (original array unchanged)

let ary1 = [10.20.30]
let ary2 =  [40.50.60]
let res = ary1.concat('arashi maple', ary2);
console.log(res)
Copy the code

3. Convert arrays to strings

The original array stays the same

toString

ToString: Converts an array to a string @params@return converted string, separated by commas (original array unchanged)

let ary = [10.20.30]
let res = ary.toString();
console.log(res) 10, 20, 30 "/ /"
console.log([].toString()) / / ""
Copy the code

join

Join: Convert an array to a string @params specified delimiter (string format) @return converted string, each entry separated by the specified delimiter (original array unchanged)

let ary = [10.20.30]
let res = ary.join(' ');
console.log(res) 10 20 to 30 "/ /"

Copy the code

4. Check whether the array contains an item

indexOf/lastIndexOf

IndexOf /lastIndexOf: Checks the first or last index value of the current item in the array (incompatible in IE6-8). @params retrieves the index value of the item @return. If the item is not present in the array, -1 is returned

let ary = [10.20.30.10.20.30]
console.log(ary.indexOf(20)) / / 1
console.log(ary.lastIndexOf(20)) / / 4
// Check if ary array contains' Arcane maple '
if(ary.indexOf('arashi maple') = = = -1) {
	/ / does not contain
}
// Use the newly provided includes method in ES6
if(ary.includes('arashi maple')) {
	// contain: returns true if present
}
Copy the code

5. Sort or arrange arrays

reverse

Reverse: Reverses the array. @return changes the original array

let ary = [12.15.9.28]
ary.reverse();
console.log(ary)
Copy the code

sort

Sort: @params can have no, or it can be a function @return after sorting the new array, the original array changes

If you do not pass an argument, you will not be able to sort numbers above 10 (it defaults to the first character).

// To sort properly, we need to pass sort a function that returns a-b ascending and b-a descending
let ary = [10.12.15.22.28.9]
ary.sort((a, b) = > {
  // A and b are adjacent terms
	 return a-b
})
console.log(ary)
Copy the code

6. Iterate over each method in the array

forEach

ForEach: Iterate over each item in the array @params callback @return the original array remains unchanged

let ary = [12.15.9.28.10.22]

// Loops based on native JS can be implemented
for(let i=0; i< ary.length; i++) {
	// I: index of the current loop item
  //ary[I]: retrieves this entry in the loop based on the index
}

ary.forEach((item, index) = > {
  // The function is executed by default as many times as there are items in the array
  // Each time the function is executed: item is the current item in the array, index is the current index
})
Copy the code

map

filter

find

reduce

some

every

Deduplicating an array

1. One way
  1. Loop through each item in the original array, adding each item to the new array
  2. Verify that this item exists in the new array before adding it
let ary = [1.2.3.1.2.1.2.1.2.3.2.1.2.3]
let newAry = [];
for(let i = 0; i< ary.length; i++) {
  
  // Loop over each item in the original array
	let item = ary[i]
  
  // Verify that this item exists in the new array
  if(newAry.includes(item)) {
    // This item exists, does not add to the new array, just continue the next loop
  	continue;
  }
  newAry.push(item)
}
console.log(newAry)
Copy the code

2. 2
  1. So let’s take each of the items in the array separately
  2. Compare this item with each item that follows it. If it encounters an item that is identical to the current item, the item is removed from the array using the splice method
var ary = [1.2.3.1.2.1.2.1.2.3.2.1.2.3];
for(var i = 0 ; i < ary.length; i++) {
  
  // item: the current item taken out of each loop
	var item = ary[i];
  // Compare the current item with each subsequent item (loop)
  for(var j= i+1; j< ary.length; j++) {
  	var compare = ary[j];
    
    // If compare and item are equal, this item is repeated, we delete it
    if(compare === item) {
    	// the j index should be removed from the array
      ary.splice(j, 1);
      
      // The array is collapsed: each index after j is advanced by one bit. The next index to be compared should be jj--; }}}Copy the code

3. A better method to delete the array
let ary = [1.2.3.1.2.1.2.3.2.1.2.3]

  // 1. Create an empty object
let obj = {}

// 2. Loop through each item in the array, store each item in the object = "item: item"
for(let i=0; i< ary.length; i++) {
	let item = ary[i]
  
  //3. Check before each storage: verify whether this item exists in OBJ
  if(obj[item] ! = =undefined) {
   // This item already exists
    ary[i] = ary[ary.length-1]
    ary.length--;
    i--;
    continue;
  }
  obj[item] = item
  
}
console.log(ary)

Copy the code

Splice-based deletion performance is poor: After the current item is deleted, the index of each subsequent item must be one bit earlier than the previous one. If there are too many subsequent items, the performance will be affected to implement the array deduplication method

@params ary[Array] the Array to be deleted @return [Array] The deleted Array

function unique(ary){
	let obj = {}
  for(let i=0; i< ary.length; i++) {
  let item = ary[i]
  if(obj[item] ! = =undefined) {
    ary[i] = ary[ary.length-1]
    ary.length--;
    i--;
  	continue;
  }
  obj[item] = item
  }
  return ary
}
console.log(unique([1.1.2.2.4.4]))
Copy the code

4. Set deduplication method based on ES6
let ary = [12.23.12.15.25.23.25.14.16]
ary = [... new Set(ary)];
console.log(ary)
Copy the code