This is the 11th day of my participation in the More Text Challenge. For details, see more text Challenge

Thinking: What should we do with all the data passed from the back end? This paper makes a comprehensive summary of the data processing methods

Data processing mode

Category:

Common changes to an array:

  • Splice () Add/delete
  • Sort () Sort an array
  • Pop () removes the last element from the array, returning that element
  • Push () adds an element to the end of the array, returning the length of the array
  • Unshift () adds one or more elements to the beginning of the array and returns the new length.
  • Reverse () Reverses the order of the elements in an array
  • Fill () fills the array

Usually not changing the original array

  • Slice () slices an array
  • Join () array to string
  • ToString () array toString
  • Cancat Splices an array
  • IndexOf () looks for the presence of an element in the array and returns the index
  • Includes () finds whether the array contains an element and returns a Boolean

Arrays are often traversed

  • forEach()
  • Every () checks whether all elements of the array meet the criteria and returns a Boolean value
  • Some () whether there are elements in the array that satisfy the criteria
  • Map () processes each element in the array and returns a new array
  • Filter () filters the array based on conditions
  • Reduce () provides an accumulator for arrays that are merged into a single value
  • Find ()& findIndex() finds array members based on conditions

1. Add values to the array

  • Add using the index of an array
let color = ["red"."blue"."green"]
// Add a value to an array
// color[1] = "yellow"
color[3] = "yellow"
console.log (color)//[ 'red', 'blue', 'green', 'yellow' ]
color[5] = "yellow"//[ 'red', 'blue', 'green', <2 empty items>, 'yellow' ]


Copy the code

2. Get the last element of the array

let color = ["red"."blue"."green".'red'.'blue'.'green']
color[color.length-1]

Copy the code

3. Convert the array to a string

    1. toString()(Without changing the array)

Returns converts an array to a string separated by commas with the array values

let color = ["red"."blue"."green"]
color.toString()
let color = ["red"."blue"."green"]
let _color = color.toString()
console.log (color)//[ 'red', 'blue', 'green' ]
console.log (_color)//"red,blue,green"

Copy the code

The toString method does not change the string representation of the original array,arrayObject

    1. join()

Returns a string of array elements with custom delimiters. If not passed, the default is separated by “,”

let color = ["red"."blue"."green"]
console.log (color.join( ))//red,blue,green
console.log (color.join(":"))//red:blue:green

Copy the code

4. Add elements to the array

  1. unshift()(change)

Unshift () changes the array and returns the size of the changed array

let color = ['a'.'b'.'c']
console.log(color.unshift('w')) / / 4
console.log(color)//[ 'w', 'a', 'b', 'c' ]

Copy the code
  1. push()

Add an element at the end of the array. According to the print, the push() method changes the array and returns the length of the changed array

let color = ['a'.'b'.'c']

console.log(color.push('w'))/ / 4
console.log (color)//[ 'a', 'b', 'c', 'w' ]

Copy the code

5. Delete elements

  1. Pop () ()

Deleting the last element in an array changes the original array, returning the deleted element

let color = ['a'.'b'.'c']
console.log(color.pop())//'c'
console.log(color)//['a,'b']

Copy the code
  1. The shift () ()

Remove the first element from the array and move all other elements to a lower index, changing the array and returning the deleted element

  let color = ['a'.'b'.'c']
  console.log (color.shift())//'a'
  console.log (color)//[ 'b', 'c' ]

Copy the code

6. Modify the array

  1. Splice (index, howmany, item1,... ,itemX)Method to add/remove items to/from the array,

Changes the original array to return the deleted items. Howmany: Number of items to be deleted. If set to 0, the item is not deleted optional. The new item added to the array.

/* Delete the array */
let color = ['a'.'b'.'c']
console.log(color.splice(1.1))//['b']
console.log(color)//[ 'a', 'c' ]
/* Add array */
let _color = ['a'.'b'.'c']
console.log(_color.splice(1.0.'pz'))//[] is null because no element was deleted
console.log(_color)//[ 'a', 'pz', 'b', 'c' ]

Copy the code
  1. slice(start,end)“Capture”

Return a new array containing the elements of the original array from start to end without changing the original array. Start specifies where to start the selection. If it’s negative, then it specifies the position from the end of the array. That is, -1 is the last element, -2 is the penultimate element, and so on. The end is optional. Specifies where to end the selection. This parameter is the array index at the end of the array fragment. If this parameter is not specified, the shred array contains all elements from start to the end of the array. If this parameter is negative, then it specifies that the elements are counted from the end of the array.

let color = ['a'.'b'.'c']
console.log(color.slice( -3, -1))//[ 'a', 'b' ]
console.log(color)//[ 'a', 'b', 'c' ]

let color = ['a'.'b'.'c']
console.log(color.slice( 1.2))//[ 'b' ]
console.log(color)//[ 'a', 'b', 'c' ]

Copy the code
  1. concat()Method is used to join two or more arrays

Returns a concatenated array without changing the original array

let man = ['a'.'b']
let woman = ['b'.'d']
let child = man.concat(woman)
console.log(child)//[ 'a', 'b', 'b', 'd' ]

Copy the code

7. Loop through the array

  1. foEachPerform the callback function once for each element in the array. The parameters of the callback function, the value of the current item in the array, the index of the current item in the array, and the array object itself, do not change the original array. The return value is undefined
let arr = ['a'.'b'.'c']
arr.forEach((item,index) = > {
  console.log (item,index)
} )
console.log (arr)


Copy the code
  1. mapReturns a new array of the return values of the callback function. Without changing the array, the callback function passes three arguments (the current element in the array being processed, and the index of the current element in the array being processed).
 let arr = [1.2.3] 
let _arr = arr.map((item,index) = >item*2)
console.log(arr) //[1, 2, 3]
console.log(_arr)//[2, 4, 6]


Copy the code
  1. everyReturn true if each element in the array satisfies the test function, false otherwise. Do not change the array
let arr = [1.2.3] 
console.log(arr.every((item,index) = > item > 2))//false

Copy the code
  1. someReturn true if at least one element in the array satisfies the test function, false otherwise. It doesn’t change the array
let arr = [1.2.3] 
console.log(arr.some((item,index) = > item > 2))//true

Copy the code
  1. The for... ofCycle: keys/value/entries
  • values()The arrayIterator () method returns a new Array Iterator containing the value of each index of the Array
  • entries()The arrayIterator () method returns a new Array Iterator containing key/value pairs for each index in the Array.
  • keys()The arrayIterator () method returns an Array Iterator containing each index key in the Array
let arr=['a'.'b'.'c']

for (let item of arr){
    console.log(item);
}
 var arr = ["abc"."bcd"."234".54.2.1];
        for (var key of arr.keys()) {
            console.log (key)/ / 0,1,2,3,4,5,6,7,8
        }
        for (var value of arr.values()){
            console.log(value)//abc bcd 234 undefined undefined undefined 54 2 1
        }
        for (var entry of arr.entries()){
            console.log(entry)
        }
// [ 0, 'abc' ]
// [ 1, 'bcd' ]
// [2, '234']
// [ 3, undefined ]
// [ 4, undefined ]
// [ 5, undefined ]
// [6, 54]
// [7, 2]
// [8, 1]

Copy the code
  1. filterPut all the array elements that return true in the filter function into a new array and return them. It doesn’t change the array
let name = ['pz'.'yjl'.'kobe'.'James']
let _name = name.filter((item,index) = > item.length > 3)
console.log(name)//[ 'pz', 'yjl', 'kobe', 'James' ]
console.log(_name)//[ 'kobe', 'James' ]

Copy the code
  1. findFind the first element that satisfies the test function and return the value of that element, or undefined if not found. It doesn’t change the array
let name = ['pz'.'yjl'.'kobe'.'James']
let _name = name.find((item,index) = > item.length > 3)
let _name2 = name.find((item,index) = > item.length > 5)
console.log(name)//[ 'pz', 'yjl', 'kobe', 'James' ]
console.log(_name)//kobe
console.log(_name2)//undefined

Copy the code

8. Convert data formats


  1. of()It converts a bunch of text or variables into an array. The method creates a new array instance with a variable number of arguments, regardless of the number or type of arguments
let arr =Array.of(3.4.5.6);
console.log(arr);//[3, 4, 5, 6]
let arr =Array.of('pz'.'yjl'.'kobe'.'James');
console.log(arr);//[ 'pz', 'yjl', 'kobe', 'James' ]

Copy the code
  1. fromCreate a new, shallow copy array instance from a similar array or iterable,JSON array format to array,JSON array format is for the front end to quickly convert JSON to array format.
let  json = {
    '0': 'a'.'1': 'bb'.'2': 'ccc'.length:3
}
let arr=Array.from(json);
console.log(arr)//[ 'a', 'bb', 'ccc' ]

console.log(Array.from([1.2.3].x= > x + x));

Copy the code

Array to heavy

Array duplication is really a very common business process in the work, so it is incumbent on us to summarize the common methods. There are actually two business situations, the first is that there are duplicates in an array and you need to remove the duplicates, and the other is to compare another array and remove the duplicates from the other array

1. There are duplicates in an array


1.1 Using Set data structure and from(ES6 common method)

ES6 provides a new data structure, Set. It is similar to an array, but the member values are unique.

eg1:
const set = new Set(a)const arr = [1.2.3.3.4.4.5]
arr.forEach(x= > set.add(x))
console.log(set)//Set { 1, 2, 3, 4, 5 }
for(let item of set) {
  console.log(item)// 1, 2, 3, 4, 5
}
//eg2:Set+ extension operator (...) Array to heavy
const set2 = new Set([1.2.3.3.4.4.5])
console.log([...set2])//[1, 2, 3, 4, 5]

Copy the code

Encapsulates the array deduplication method

const unique = arr= > Array.from(new Set(arr))// Wrap the function
const arr = [1.2.3.3.4.4.5]
let uniqueArr = unique(arr)/ / substitute
console.log(uniqueArr)//[1, 2, 3, 4, 5]

Copy the code

This is the least code method

For loop +splice

/* Does the element in the loop have the same */ following it
const unique = arr= > {
  for (let i = 0; i < arr.length; i++) {
    for(let j = i+1; j < arr.length-1; j++) {
      if (arr[i]===arr[j]) {
        arr.splice(i,1)
        i--
      }
    }
  }
  return arr
}
/* Another way to write this is if the element of the loop is not preceded by the same */ as the element
const unique = arr= > {
  for (let i = 0; i < arr.length; i++) {
    for(let j = 0; j < i; j++) {
      if (arr[i]===arr[j]) {
        arr.splice(i,1)
        i--
      }
    }
  }
  return arr
}
/* Methods that do not change the original array */
const unique = (arr,uniqueArr ) = > {
  for (let i = 0; i < arr.length; i++) {
    for(let j = i+1; j < arr.length; j++) {
      if (arr[i]===arr[j]) {
        j=++i
      }
    }
    uniqueArr.push(arr[i])
  }

}
const arr = [1.2.3.3.4.4.5]
let uniqueArr= new Array()
unique(arr,uniqueArr)
console.log(uniqueArr)

Copy the code

1.3 Indexof ()+for loop does not change the edge of the array

const unique = (arr,uniqueArr ) = > {
  if (!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
  for (let i = 0; i < arr.length; i++) {
    uniqueArr.indexOf (arr[i]) === -1 && uniqueArr.push(arr[i])
  }
}
const arr = [1.2.3.3.4.4.5]
let uniqueArr= new Array()
unique(arr,uniqueArr)
console.log(uniqueArr)

Copy the code

1.4 the filter () + indexOf ()

const unique = arr= > arr.filter((item,index) = > arr.indexOf(item)===index) 
const arr = [1.2.3.3.4.4.5]
let uniqueArr= unique(arr)
console.log(uniqueArr)

Copy the code

1.5 Reduce the number of loops (fast) by using the feature that the attributes of the object cannot be the same

const unique = (arr,uniqueArr ) = > {
  if (!Array.isArray(arr)) {
        console.log('type error! ')
        return
    }
  let tag = {}
  for (let i = 0; i < arr.length; i++) {
    if(! tag[arr[i]]) { uniqueArr.push(arr[i]) tag[arr[i]]=true}}}const arr = [1.2.3.3.4.4.5]
let uniqueArr= new Array()
unique(arr,uniqueArr)
console.log(uniqueArr)

Copy the code

2. Remove identical items from two arrays (often encountered at work)


Use filter to filter arrays

const a=[1.2.3.4.5]
const b=[2.3.7.8.9]
console.log(a.filter(item= >b.indexOf(item)===-1))
console.log(a.filter(item= >! b.some(e= > e === item)))
console.log(a.filter(v= >! b.includes(v)))console.log(a.filter(item= > b.every(e= >e! == item)))Copy the code

If this article is useful to you, welcome to like forwarding attention, let more friends see ah, after all, sharing is the most basic virtue of a programmer!! If there is wrong, please instruct the boss.)